Search a folder tree (sorted)
Remove the sorted(...) calls: the code still runs, but you can no longer rely on the order. Always sort before printing.
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
top level : ['about.html', 'blog', 'index.html', 'logo.png']
*.html here: ['about.html', 'index.html']
all *.html : ['site/about.html', 'site/blog/post1.html', 'site/blog/post2.html', 'site/index.html']
all *.png : ['site/blog/img/cover.png', 'site/logo.png']