pathlib represents filesystem paths as objects with operations for examining and constructing locations.
Work with names, suffixes and joins while distinguishing a path value from evidence that a file exists or can be opened.
A report named sales.backup.csv must become sales.backup.json. Which part of the name should change, and which must stay? A path object lets you answer that structural question without guessing where to slice a string. Start with names, then inspect real files, and finally separate path manipulation from access control.

Rename every export to .json
A nightly job converts each CSV export to JSON, same name, new extension. Hand-written string surgery breaks the moment a filename has more than one dot:
from pathlib import PurePosixPath
p = PurePosixPath("exports/2026/sales.backup.csv")
print(p.stem)with_suffix does the swap correctly, because it only ever touches the last
suffix, exactly like stem only ever strips the last one:
Paths are immutable, like strings — every one of those calls returns a new
path, and src itself never changes. relative_to is the method Quarry
leans on hardest: it walks a folder with absolute paths on disk, but a report
should say 2026/sales.backup.csv, not /tmp/tmpk2x9d/exports/2026/....
Stripping the root off with relative_to(root) is exact, where slicing the
string by its length breaks the moment there's a trailing slash.
Preparing this topic’s interactive investigation…
Join a report path from a config file
Quarry reads a filename out of a config file and joins it onto the output
folder. The / operator looks like string concatenation, but it isn't one:
TypeErrorRun it and read the TypeError. Then join the two parts the pathlib way.
/ has one rule that surprises everybody once, and it's exactly the kind of
thing a config file can trigger by accident:
from pathlib import PurePosixPath
print(PurePosixPath("yard") / "logs" / "/etc/hosts")That's why "just join whatever the config says" is a security bug: a
filename of /etc/hosts or ../../etc/passwd silently escapes the folder
Quarry meant to write into. The exercise checks is_absolute() and walks .parts to reject lexical
escape through ... That is one useful check; it does not account for
symbolic links or concurrent filesystem changes.
A path describes a location; it does not reserve it
Start with three different questions: what name did I construct, what exists there now, and what may this program access? PurePosixPath answers the first without touching a filesystem. Path.is_file() asks the second. Neither operation establishes the third.
Consider yard/reports/today.json. A lexical check sees no absolute component and no ... But if reports is a symbolic link to another directory, opening the path follows that link. Rejecting .. alone therefore cannot guarantee that a write stays inside yard. Even resolving the path and checking its parent can race with a later filesystem change. The safe_join exercise deliberately teaches lexical normalization; it is not a secure file-opening API.
For the inventory, separate selection from presentation:
| Candidate | Reason to include or exclude | Report name |
|---|---|---|
yard/data/A.CSV |
file; suffix matches after lowercasing | data/A.CSV |
yard/.cache/A.csv |
hidden ancestor; exclude | no row |
yard/data/archive.csv/ |
directory; exclude even though suffix matches | no row |
Lowercase the suffix for comparison; keep the original spelling in the report. Sorting the result makes tests and diffs stable; traversal order is not a contract.
Try a different inventory: include .json and .JSON, exclude a directory named old.json, and keep two distinct files named A.json and a.json when the underlying filesystem permits both. Explain why lowercasing the whole path would destroy information. The browser examples use a temporary virtual filesystem, not your computer's folders.
Reference: path objects, resolution and filesystem operations.
Find every log in a shared yard
A yard holds logs/app.log, logs/old/app.log, a hidden editor cache
.cache/stale.log, and notes.txt. glob and rglob find files by
pattern instead of listing everything and filtering by hand:
| pattern | matches |
|---|---|
*.log |
any name ending .log, in this folder only |
**/*.log |
any .log at any depth, this folder included |
data/*/q?.csv |
q plus any one character then .csv, one level under data/ |
* never crosses a /; ** is the part that descends. rglob("*.log") is
shorthand for glob("**/*.log") — recursive glob. Here is the yard the next
example builds, as a picture:
Predict what each pattern finds before you run it: *.log from yard/ finds
nothing (there is no log at the top), logs/*.log finds one, and
rglob("*.log") finds all three — including the one inside the hidden
.cache/ folder:
That last line is the trap Quarry has to handle: rglob happily walks into
hidden folders too. Editor caches, version-control internals and trash
folders are all "hidden" on POSIX systems by the convention that their name
starts with a dot — and rglob doesn't know or care about that convention.
Checking rel.parts for any part starting with . catches a hidden file
or a file anywhere inside a hidden folder:
from pathlib import PurePosixPath
rel = PurePosixPath("srv/.cache/x.log")
print(any(part.startswith(".") for part in rel.parts))Patterns match names, and you can test that matching with no disk at all. Step
through this and watch which names survive — notice that * refuses to
swallow the old/ level:
Two lessons in one trace: * stays inside one level, and matching is
case-sensitive on POSIX paths, so app.LOG is not a .log. Real yards
contain both spellings, which is why Quarry lowers the suffix before
comparing.
Quick practice
from pathlib import PurePosixPath
p = PurePosixPath("archive.tar.gz")
print(p.suffix, p.suffixes)TypeErrorRun it, read the error, then join the pathlib way.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
yard = Path(tmp)
(yard / "a" / "b").mkdir(parents=True)
(yard / "a" / "b" / "deep.log").write_text("x", encoding="utf-8")
(yard / "top.log").write_text("x", encoding="utf-8")
print(sorted(p.name for p in yard.glob("*.log")))from pathlib import PurePosixPath
print(PurePosixPath("data") / "/backup" / "q1.csv")🎯 Your turn
Build find_sources(files, suffixes):
find_sources({"logs/a.log": "", "notes.txt": "", "data/X.CSV": ""}, [".log", ".csv"])→["data/X.CSV", "logs/a.log"]find_sources({".git/config.log": "", "srv/app.LOG": ""}, [".log"])→["srv/app.LOG"]
Hint — walk with rglob("*"), keep is_file(), skip hidden parts of
relative_to(root), compare suffix.lower(), and sort the POSIX strings.
Then press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write path_parts(path) returning [parent, name, stem, suffix] for a POSIX path string, each as a string. Use PurePosixPath so nothing touches a disk. path_parts("logs/2026/app.log") → ["logs/2026", "app.log", "app", ".log"].
Write swap_suffix(path, new_suffix) returning the POSIX path string with its suffix replaced (or added, if there was none). swap_suffix("data/report.csv", ".json") → "data/report.json".
Write list_tree(files). Plant the files in a temporary folder (use the helper in the starter), then return every path under it — files AND folders — as sorted relative POSIX strings, with folders marked by a trailing /. list_tree({"logs/a.log": ""}) → ["logs/", "logs/a.log"].
Quarry reads relative paths out of config files, and a hostile one might say ../../etc/passwd. Write safe_join(root, relative): return the joined POSIX path string with every . and .. resolved, or None if relative is absolute or climbs out of root. Work on the path's parts only — no disk. safe_join("yard", "logs/../b.txt") → "yard/b.txt".
Write inventory(files). Plant the files, walk them, and return {"count": n, "by_suffix": {...}, "deepest": path} where by_suffix counts files per lower-cased suffix (use "(none)" for no suffix) and deepest is the relative POSIX path with the most parts (alphabetically first on a tie, "" if there are no files).
A teammate writes folder + "/" + name everywhere and says pathlib is just decoration. Explain, with at least one concrete failure, why Quarry keeps paths as Path objects inside the program and only turns them into strings at the edges.