Read and Write Files Safely in Python
Use pathlib, context managers and explicit encodings for reliable file operations.
Read a text file
from pathlib import Pathtext = Path("notes.txt").read_text(encoding="utf-8")
print(text)
Write a file
Path("output.txt").write_text("Learning Python\n", encoding="utf-8")Choose whether to replace or append to existing content.
Process large files line by line
with open("access.log", encoding="utf-8") as file:for line in file:
if "ERROR" in line:
print(line.rstrip())
Iterating line by line avoids loading the whole file into memory.
Handle expected errors
try:content = Path("missing.txt").read_text(encoding="utf-8")
except FileNotFoundError:
print("File not found")
except OSError as error:
print(f"Could not read file: {error}")
Catch specific exceptions rather than silently hiding failures.
Keep learning
Try the concepts in a small project and verify version-specific details with official documentation.
More Python resources