Text, Encodings, and Context Managers
Unit ID: M07-U02 Estimated active time: 22-30 minutes
Open text with an explicit encoding
from pathlib import Path
note_path = Path("output") / "note.txt"
with note_path.open("w", encoding="utf-8") as file:
file.write("Fictional course conversion complete.\n")
The with block closes the file even if an exception occurs inside the block.
Read it:
with note_path.open("r", encoding="utf-8") as file:
note = file.read()
File modes matter
"r": read; file must exist."w": write; creates or replaces the file."a": append; adds at the end."x": exclusive creation; fails if the file exists.
The "w" mode can destroy an existing file. Never point it at the supplied source path.
Text encoding
An encoding maps stored bytes to characters. Use UTF-8 for course text files unless the source contract says otherwise.
Reading with the wrong encoding can raise UnicodeDecodeError or produce incorrect characters. Do not suppress the error and continue with damaged text.
Read size consciously
file.read() loads all text into memory. That is acceptable for the tiny supplied course files. Large-file processing needs a different design and is outside this module.
Preserve line endings through structured tools
When using Python's CSV module, open text files with newline="" so the CSV parser controls newline handling consistently.
Practice
Write a small UTF-8 note to an output folder, read it back, and assert the exact text. Then explain why "w" must never target the supplied source file.
Takeaway
Use context managers, explicit encodings, and deliberate modes. Writing is a potentially destructive action, so separate outputs from source evidence. Next, we will parse CSV structure without manual string splitting.
