Pieces of a path
Creating a Path does not touch the disk, so these file names do not need to exist.
pathlib.Path represents a file or folder location as an object. You join parts with /, ask questions like exists(), read and write with one call, search with glob, and your code works on Windows, macOS and Linux alike.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 7 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given p = Path("photos/trip/beach.jpeg"), print its name, stem, suffix and the name of its parent folder on one line, separated by spaces. Hint: the parent is itself a Path, so it has a .name too.
Create the folder out/logs (with mkdir). Write the text ok into out/logs/a.log and out/logs/b.log. Then print a list of the names of all .log files under out, in sorted order. Hint: rglob("*.log") searches every subfolder.
Write file_size(path) that returns the size in bytes of a file, or -1 if it does not exist. Do not use try/except; check first with is_file(). Hint: p.stat().st_size is the size.
Explain it without notes
Why use pathlib.Path instead of joining strings with + or os.path.join?
What is the difference between a relative and an absolute path, and how do you find the folder that holds the current script?
Why must you sort the results of glob and iterdir?
What do mkdir(parents=True, exist_ok=True) and shutil.rmtree do, and what are their dangers?
Expected output
path : data/reports/summary.final.txt
name : summary.final.txt
stem : summary.final
suffix : .txt
parent : data/reports
parts : ('data', 'reports', 'summary.final.txt')
as .md : data/reports/summary.final.md
absolute?: False
archive : ['.tar', '.gz']