Read a text file

from pathlib import Path

text = 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.