October 13, 2024

How to Write in a Text File Using Python

Writing to a text file in Python is a common task, and it can be accomplished using various methods provided by Python’s built-in functions. This guide will walk you through the basics of writing to a text file, including appending to a file and handling file paths.

1. Writing to a Text File

To write to a text file, use the open() function with the mode 'w' (write) or 'a' (append). The 'w' mode will create a new file or overwrite an existing file, while 'a' will append to the existing file.

1.1 Writing to a New File or Overwriting an Existing File

# Open a file in write mode
with open('example.txt', 'w') as file:
    file.write("Hello, world!n")
    file.write("This is a new line.")

Using the with statement ensures that the file is properly closed after writing.

1.2 Appending to an Existing File

# Open a file in append mode
with open('example.txt', 'a') as file:
    file.write("nThis line is appended to the file.")

2. Writing Multiple Lines

To write multiple lines to a file, you can use a loop or the writelines() method:

# Using a loop
lines = ["First linen", "Second linen", "Third linen"]
with open('example.txt', 'w') as file:
    for line in lines:
        file.write(line)

# Using writelines()
with open('example.txt', 'w') as file:
    file.writelines(lines)

3. Writing Formatted Strings

You can use string formatting to write formatted text to a file:

# Write formatted strings
name = "Alice"
age = 30
with open('example.txt', 'w') as file:
    file.write(f"Name: {name}n")
    file.write(f"Age: {age}n")

4. Handling File Paths

When dealing with file paths, you can use absolute or relative paths. Python’s os module can help with path manipulations:

import os

# Define a relative path
file_path = 'data/example.txt'

# Ensure the directory exists
os.makedirs(os.path.dirname(file_path), exist_ok=True)

# Write to the file
with open(file_path, 'w') as file:
    file.write("This is a file in a nested directory.")

5. Summary

Writing to a text file in Python is straightforward using the open() function with the appropriate mode. You can write single lines, multiple lines, or formatted strings and handle file paths effectively. Using the with statement ensures proper file handling and closure.