Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.6 — Paths the Modern Way: pathlib
Python · Example 1 of 4

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.

01

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.

02

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.

03

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

01

Why use pathlib.Path instead of joining strings with + or os.path.join?

02

What is the difference between a relative and an absolute path, and how do you find the folder that holds the current script?

03

Why must you sort the results of glob and iterdir?

04

What do mkdir(parents=True, exist_ok=True) and shutil.rmtree do, and what are their dangers?

Pieces of a path
Sign in to run this example in your browser.

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']