Sub topic 3
One-Call Reads and Writes with `pathlib`
Assume you know basic Python syntax, loops, functions, try/except, and the difference between str and bytes. pathlib gives you objects for filesystem paths and convenient methods for common file operations.
One-call reads and writes with `pathlib`
Build paths with /. This works across operating systems. write_text() creates or replaces a file, while read_text() reads the whole file.
from pathlib import Path
path = Path("data") / "greeting.txt"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("héllo\n", encoding="utf-8")
print(path.read_text(encoding="utf-8"))These methods load or write the complete file. For large files, iterate over the file instead.
Handling missing files and permission errors
Catch errors at the operation that can fail. FileNotFoundError means the path does not identify an existing file. PermissionError means the operating system refused access.
try:
text = Path("missing.txt").read_text(encoding="utf-8")
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("The file cannot be read.")Binary files and reading in chunks
Use binary mode, rb and wb, for images, archives, and other non-text data. Read large files in chunks so memory use stays bounded.
with open("input.bin", "rb") as source, open("copy.bin", "wb") as target:
while chunk := source.read(64 * 1024):
target.write(chunk)Reading and writing CSV and JSON
Use csv for rows and columns. Use json for nested Python dictionaries and lists.
import csv
import json
rows = [{"name": "Ada", "age": 36}, {"name": "Linus", "age": 28}]
with open("people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows(rows)
with open("people.json", "w", encoding="utf-8") as f:
json.dump(rows, f, indent=2)The newline="" argument lets the CSV module control line endings.
Moving around a file with `seek()` and `tell()`
A file object has a current position. tell() reports it, and seek() moves it.
with open("notes.txt", encoding="utf-8") as f:
first = f.read(5)
position = f.tell()
f.seek(0)
whole_file = f.read()Writing files safely with a temporary file
Writing directly can leave a partial file if the process crashes. Write a temporary file in the destination directory, then replace the original.
import os
import tempfile
from pathlib import Path
def atomic_write(path, text):
path = Path(path)
fd, temporary = tempfile.mkstemp(dir=path.parent)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(text)
f.flush()
os.fsync(f.fileno())
os.replace(temporary, path)
except BaseException:
Path(temporary).unlink(missing_ok=True)
raiseExercise
Which method should you use to copy a large image without loading it all into memory?
Show answer
Open the files with rb and wb, then read and write fixed-size byte chunks.