Learn the concept
A path identifies a filesystem location. Relative paths depend on the process’s working directory, which may differ between an editor, terminal, and server. Use pathlib to compose paths and document where inputs and outputs belong.
Choose an explicit encoding when reading text. A file may be missing, unreadable, or not valid in that encoding. Handle those outcomes without pretending you successfully processed an empty document. Opening a file for writing can overwrite existing content, so choose output names deliberately.
Temporary directories are useful for tests because they isolate side effects and clean up afterwards. When accepting user-supplied paths, validate that the resolved path stays within the intended data directory. String concatenation alone is not a security boundary.
Run and inspect
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "note.txt"
path.write_text("café", encoding="utf-8")
assert path.read_text(encoding="utf-8") == "café"
Your exercise
Read three files from a temporary folder and report missing or undecodable files separately. Write results to a different output path.
Check your understanding
Input files are preserved and each file has a recorded success or failure outcome.