Find your way around.
Build paths without hard-coded separators, and discover files deliberately.
01 The idea
A path describes a location; it is not the file itself. pathlib gives paths operations that read like the actions you intend: create a folder, discover matching files, or inspect a suffix. Relative paths start from the process working directory, which may differ from the directory containing your script. Start a file-processing job by deciding which directory it owns and which inputs it accepts.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from pathlib import Path
folder = Path("incoming")
folder.mkdir(exist_ok=True)
(folder / "brief.txt").write_text("Orbit", encoding="utf-8")
(folder / "notes.csv").write_text("name,minutes\nBuild,40\n", encoding="utf-8")
for path in sorted(folder.glob("*.txt")):
print(path.name, path.suffix, path.is_file())brief.txt .txt True
03 Under the hood
- 1
The / operator joins path components without making you choose a slash style. mkdir(exist_ok=True) makes repeated practice runs convenient.
- 2
glob("*.txt") searches one directory level. rglob("*.txt") descends through subdirectories; use it only when recursive discovery is intended. Sorting gives predictable processing order.
- 3
Resolve user-provided paths and check they stay under an approved directory before using them in a service. An extension is a naming convention, not proof of file contents.
04 Your turn, builder
List only .csv files in incoming, in sorted order.
Reveal one possible solution +
from pathlib import Path
folder = Path("incoming")
folder.mkdir(exist_ok=True)
(folder / "tasks.csv").write_text("task\nBuild\n", encoding="utf-8")
print([p.name for p in sorted(folder.glob("*.csv"))])05 Check your signal
What does rglob add to glob?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.