Working with Files
Python's with statement closes files reliably, including when an error occurs.
Python's with statement closes files reliably, including when an error occurs.
Reading text
from pathlib import Path
path = Path("events.log")
text = path.read_text(encoding="utf-8")
print(text)
For large files, iterate line by line:
with path.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
if "ERROR" in line:
print(line.rstrip())
Writing safely
output = Path("report.txt")
output.write_text("Analysis complete\n", encoding="utf-8")
Before overwriting a file, confirm the destination and consider writing to a temporary file first. Never build privileged paths directly from untrusted input.
JSON data
import json
data = {"completed": True, "score": 10}
Path("progress.json").write_text(
json.dumps(data, indent=2), encoding="utf-8"
)
Handle missing files, invalid encoding and malformed structured data explicitly.