File handling
Set up interfaces and contracts
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
Setup the chapter step
The required setup is: Python 3 runs from a folder containing a small labels.txt fixture. Confirm it before copying code. The contract separates input from output: UTF-8 lines that may contain blank space, duplicate labels, and mixed capitalization goes in, and one normalized label per line in a new file comes out. If either side is ambiguous, later debugging will chase the wrong layer.
The input contract is UTF-8 lines that may contain blank space, duplicate labels, and mixed capitalization. The visible result is one normalized label per line in a new file.
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
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.
For the current setup 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.
Read every command or statement before running it. The examples deliberately expose intermediate state so a surprising result has somewhere concrete to point.
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?