Paths with pathlib
Scenario: A script works only from one current directory because paths are joined by hand.
New words, in plain English
- Path - a location in a filesystem
- Current working directory - the folder relative paths start from
- pathlib - the standard library's object-oriented path toolkit
Path joins with /, tests existence, creates directories, lists entries, and reads/writes small files. Resolve paths relative to a known base rather than assuming where the user launched the script.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
from pathlib import Path
base = Path(__file__).resolve().parent
reports = base / "output"
reports.mkdir(exist_ok=True)
(reports / "ready.txt").write_text("yes
", encoding="utf-8")
Tip: Use mkdir(parents=True, exist_ok=True) for a safely repeatable directory tree.
Goal: Practice this idea in the py-read-file challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.