Python: Reading and Writing Text Files
This tutorial will guide you through reading and writing text files using Python. We’ll cover basic file operations, including opening, reading, writing, and closing files. We’ll focus on clear, concise code with explanations and practical examples.
Example 1: Writing to a File
The first example demonstrates how to write a simple string to a text file. This is the fundamental building block for more complex file handling.
import os
def write_to_file(filename, content):
"""Writes the given content to a file.
Args:
filename: The name of the file to create or overwrite.
content: The string to write to the file.
"""
try:
with open(filename, 'w') as f: # 'w' mode for writing, opens and closes automatically
f.write(content)
print(f"Successfully wrote to {filename}")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage:
filename = "my_file.txt"
content = "Hello, world!nThis is a new line."
write_to_file(filename, content)
In this code:
- We import the `os` module, although it’s not strictly necessary for this simple example. It’s good practice to include it in file operations, as it provides tools for interacting with the operating system and file paths.
- We define a function `write_to_file` that takes a filename and content as arguments.
- We use a `try…except` block to handle potential errors (e.g., file not found, permission issues).
- The core of the function is the `with open(filename, ‘w’) as f:` statement. This opens the file in write mode (‘w’). The `with` statement ensures the file is automatically closed, even if errors occur. The `as f` assigns the file object to the variable `f`.
- `f.write(content)` writes the `content` string to the file.
- We print a success message or an error message depending on whether the write operation was successful.
Common Mistake: Forgetting to close the file. The `with` statement handles this automatically, but if you were to use `f.close()` manually, you’d need to ensure it’s called, even in error cases, to release the file resource.
Explanation: The file is opened in write mode (‘w’). This means that if the file already exists, its contents will be overwritten. If the file does not exist, a new file will be created. The `with` statement is crucial because it guarantees the file is properly closed, even if an exception is raised. Without it, you would need to explicitly call `f.close()` to release the file resource.
# Example Usage:
filename = "my_file.txt"
content = "Hello, world!nThis is a new line."
write_to_file(filename, content)
The content “Hello, world!nThis is a new line.” will be written to a file named “my_file.txt”. If “my_file.txt” already existed, its content would be replaced.
Output:
Successfully wrote to my_file.txt
Example 2: Reading from a File
This example demonstrates how to read the contents of a file and print them to the console. We’ll use the ‘r’ mode for reading.
def read_from_file(filename):
"""Reads the contents of a file and prints them to the console.
Args:
filename: The name of the file to read.
"""
try:
with open(filename, 'r') as f:
for line in f:
print(line, end='') # end='' prevents adding an extra newline
except FileNotFoundError:
print(f"File not found: {filename}")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage:
filename = "my_file.txt"
read_from_file(filename)
In this code:
- We define a function `read_from_file` that takes a filename as an argument.
- We use a `try…except` block to handle potential errors.
- The `with open(filename, ‘r’) as f:` statement opens the file in read mode (‘r’).
- We iterate through the file line by line using a `for` loop.
- `print(line, end=”)` prints each line to the console. The `end=”` argument prevents the `print` function from adding an extra newline character after each line, as the lines read from the file already include newline characters.
- We handle `FileNotFoundError` specifically, printing a user-friendly message.
Explanation: The file is opened in read mode (‘r’). The `for line in f:` loop efficiently reads the file line by line without loading the entire file into memory. This is important for large files. The `end=”` argument in the `print` function is used to prevent double newlines, ensuring the output looks as intended.
# Example Usage:
filename = "my_file.txt"
read_from_file(filename)
Assuming “my_file.txt” exists with the content “Hello, world!nThis is a new line.”, the output will be:
Output:
Hello, world!
This is a new line.
Example 3: Appending to a File
This example shows how to append new content to an existing file. We’ll use the ‘a’ mode for appending.
def append_to_file(filename, content):
"""Appends the given content to a file.
Args:
filename: The name of the file to append to.
content: The string to append to the file.
"""
try:
with open(filename, 'a') as f:
f.write(content + 'n')
print(f"Successfully appended to {filename}")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage:
filename = "my_file.txt"
content = "This is appended content."
append_to_file(filename, content)
In this code:
- We define a function `append_to_file` that takes a filename and content as arguments.
- We use the ‘a’ mode for opening the file. This means that if the file already exists, the new content will be added to the end of the file. If the file does not exist, a new file will be created.
- `f.write(content + ‘n’)` writes the `content` to the file followed by a newline character. The newline character ensures that the new content is on a separate line in the file.
Explanation: The file is opened in append mode (‘a’). This ensures that any new content written to the file is added to the end of the existing content. The `n` character is added to the end of the content to ensure that the new content is written on a new line in the file.
# Example Usage:
filename = "my_file.txt"
content = "This is appended content."
append_to_file(filename, content)
If “my_file.txt” initially contained “Hello, world!nThis is a new line.”, after running this code, the file will contain:
Output:
Hello, world!
This is a new line.
This is appended content.



Leave a Reply