File handling
Mastery: ship checklist
File handling moves durable data between program runs; explicit paths, encodings, and write destinations keep that handoff predictable.
Before you start
Why this matters
Before running anything, predict one observable result from the case: a noisy labels.txt must become a lowercase, de-duplicated clean-labels.txt without overwriting the source. Write the prediction beside the command or code line that should cause it. This makes the session an experiment rather than a transcription exercise.
1Learn the idea
Read
Ship the chapter step
Shipping means handing off evidence, not only source code. Include a tiny sample input, expected output, and whether writing replaces an existing target. For large datasets, document a streaming variant using with source.open(...). Rebuild or rerun from the documented starting point. If another person needs an undocumented fact from your machine, the handoff is incomplete.
Keep the example small enough to inspect manually. Small does not mean careless: boundary values, file locations, feature order, and held-out data still determine whether the result means what you claim.
Read
Run the working example
from pathlib import Path
source = Path("labels.txt")
target = Path("clean-labels.txt")
lines = source.read_text(encoding="utf-8").splitlines()
clean = list(dict.fromkeys(
line.strip().lower() for line in lines if line.strip()
))
target.write_text("\n".join(clean) + "\n", encoding="utf-8")
print(f"read {len(lines)}; saved {len(clean)}")
Expected evidence:
read 5; saved 3
The output may include version-specific details such as hashes, paths, fitted thresholds, or final decimal places. Compare the structural facts described here rather than copying placeholders. If the structure differs, stop and inspect the earliest unexpected line.
Read
Read it line by line
Pathkeeps path operations clearer than manual slash concatenation.read_textdecodes bytes as UTF-8 andsplitlinesremoves line endings.- the generator normalizes values, while
dict.fromkeysremoves duplicates without changing first-seen order. write_textreplaces the target and returns a byte count; the source path is never opened for writing.
These lines form one chain: UTF-8 lines that may contain blank space, duplicate labels, and mixed capitalization becomes one normalized label per line in a new file. Change only one input first. When several values change together, you cannot tell which change caused the new behavior.
Read
Common errors and fixes
- First failure:
FileNotFoundErrorincludes the unresolved path; printsource.resolve()to verify the current working directory. Re-run the smallest command that proves the repair. - Second failure:
UnicodeDecodeErrormeans the declared encoding does not match the bytes. Preserve the failing input as a test when it represents a realistic mistake. - Misleading success:
PermissionErroror a partial write needs a safe destination; critical workflows should write a temporary file and replace only after success. A clean-looking final line cannot cancel contradictory intermediate evidence.
When debugging, copy the exact error text and inspect names, paths, shapes, types, and versions. Explain the cause in one sentence before changing code. That discipline prevents a guessed repair from creating a second defect.
Read
Evidence for this stage
The deliverable for this step is a script that reads UTF-8 text, cleans non-empty labels, writes atomically to a separate path, and reports counts.
For the current ship step, save the smallest useful evidence: the relevant command, its output, and the input that produced it. Do not use a screenshot as the only record when text can be copied and searched. Keep generated artifacts separate from source inputs so rerunning the example does not destroy the evidence it is meant to evaluate.
Reject paths outside the intended data directory when users choose filenames. Avoid logging file contents that may contain personal data, and never build paths by blindly appending untrusted ../ segments.
Read
Reflect on the result
Return to your opening prediction. Mark it correct or rewrite it with the condition you missed. Then explain the difference between a successful execution and a trustworthy result for this specific example.
Continue learning · glossary & guides
- Which line or command establishes the current step's most important fact?
- What output would reveal that
UnicodeDecodeErrormeans the declared encoding does not match the bytes? - Can a new user reproduce a script that reads UTF-8 text, cleans non-empty labels, writes atomically to a separate path, and reports counts from the stated setup?