Tutorials · Chapter D (4/4) · ~9 min
File handling
Try it → see it → read → next
Read, transform, and save a small text file without leaking resources or data.
Try yourself
Code Lab
Data: tables & simple stats
Run the average, then print the top student name.
Recap
What you just did
You moved data through a complete file loop: open → read → transform → write. Using a with block also closed the file automatically, even if later code failed. That habit matters once files become datasets and model artifacts.
Teach
How it works
from pathlib import Path
source = Path("labels.txt")
lines = source.read_text(encoding="utf-8").splitlines()
clean = [line.strip().lower() for line in lines if line.strip()]
Path("clean-labels.txt").write_text(
"\n".join(clean),
encoding="utf-8",
)
print(f"saved {len(clean)} labels")
For larger or streamed files, use with source.open(...) as file: and process one line at a time.
- Path identifies where data lives
- Read turns bytes into text or records
- Transform makes the data useful
- Write persists an artifact you can inspect
Mental model: files are handoff points between program runs.
Use it
When you'd use this
- Loading prompt examples or labels from disk
- Saving cleaned data before model training
- Writing predictions and logs for later review
Watch out
Watch out
Opening with write mode can replace an existing file. Check the target path before saving. Specify text encoding, avoid loading enormous files all at once, and never print secrets from configuration files into logs.
Try next
Try this next
Add one duplicate label, then update the transform so the output contains each label once.