Example output
Here is a Python code snippet that demonstrates reading, writing, and appending data to a text file with error handling, following best practices:
```python
# Import necessary modules for error handling
import os
# Define a function to write data to a file
def write_to_file(file_path, data):
"""
Write data to a specified text file, overwriting if it exists.
Parameters:
- file_path (str): The path to the file.
- data (str): The data to write to the file.
"""
try:
with open(file_path, 'w', encoding='utf-8') as file: # Open in write mode, UTF-8 encoding for compatibility
file.write(data) # Write data to the file
print(f"Data successfully written to {file_path}")
except PermissionError:
print(f"Permission denied: Cannot write to {file_path}")
except Exception as e:
print(f"An error occurred while writing to {file_path}: {e}")
# Define a function to append data to a file
def append_to_file(file_path, data):
"""
Append data to a specified text file.
Parameters:
- file_path (str): The path to the file.
- data (str): The data to append to the file.
"""
try:
with open(file_path, 'a', encoding='utf-8') as file: # Open in append mode
file.write(data) # Append data to the file
print(f"Data successfully appended to {file_path}")
except PermissionError:
print(f"Permission denied: Cannot append to {file_path}")
except Exception as e:
print(f"An error occurred while appending to {file_path}: {e}")
# Define a function to read data from a file
def read_from_file(file_path):
"""
Read and return data from a specified text file.
Parameters:
- file_path (str): The path to the file.
Returns:
- str: The content of the file or an empty string if an error occurs.
"""
try:
with open(file_path, 'r', encoding='utf-8') as file: # Open in read mode
content = file.read() # Read entire content
print(f"Data successfully read from {file_path}")
return content
except FileNotFoundError:
print(f"File not found: {file_path}")
except PermissionError:
print(f"Permission denied: Cannot read from {file_path}")
except Exception as e:
print(f"An error occurred while reading from {file_path}: {e}")
return "" # Return empty string if reading fails
# Usage example
file_path = "example.txt"
write_data = "This is an example of writing to a file.\n"
append_data = "This is additional data appended to the file.\n"
# Write data to the file
write_to_file(file_path, write_data)
# Append data to the file
append_to_file(file_path, append_data)
# Read data from the file
content = read_from_file(file_path)
if content:
print("File Content:\n", content)
```
### Explanation of Code:
- **Functions for Modularity**: Separate functions (`write_to_file`, `append_to_file`, and `read_from_file`) make it easy to reuse or modify these operations for different files.
- **Error Handling**:
- Catches `PermissionError` for cases where the program lacks permissions to modify/read the file.
- Catches `FileNotFoundError` in the read function to handle cases where the file does not exist.
- General `Exception` handling for any other unexpected errors.
- **File Handling Best Practices**: Uses `with open(...) as file`, which ensures files are automatically closed after operations, even if an error occurs.
- **UTF-8 Encoding**: Specifies encoding to ensure compatibility across platforms and avoid unexpected encoding issues.
This modular design can be extended by calling these functions with different file paths or data content, making the code reusable and maintainable.