Working with Paths and the Filesystem
Build, inspect and traverse file paths portably with pathlib and os
Big idea: In the beginner course you opened a file by hard-coding its name. Real programs rarely know the exact path ahead of time: they build it from pieces, check whether it exists, list what is in a folder, and walk whole directory trees. Python's modern tool for this is
pathlib.Path - an object that treats a path as structured data rather than a fragile string. The older os module still fills a few gaps, so you will meet both.
By the end you will be able to:
- explain why joining paths with
"+"and"/"breaks across operating systems, - build paths safely with
Pathand the/operator, - read a path apart with
.name,.stem,.suffix,.parentand.parts, - test existence and type with
.exists(),.is_file(),.is_dir(), - create folders with
.mkdir(parents=True, exist_ok=True), - list and filter directory contents with
.iterdir(),.glob()and.rglob(), - walk an entire folder tree and know when to reach for
osinstead.
1. The problem: paths are not just strings
A path looks like an ordinary string, so the tempting first instinct is to glue pieces together with +:
folder = "data"
name = "report.txt"
path = folder + "/" + name # "data/report.txt" - fragile!
This works by luck, not by design. Two real problems hide in it:
- Separators differ. Linux and macOS separate folders with a forward slash
/; Windows uses a backslash\. Hard-coding one breaks the other machine. - Edge cases pile up. Does
folderalready end with a slash? Is a part empty? String maths forces you to handle each case by hand, and one missed case corrupts the path.
pathlib solves this by making a path an object that knows how to join, split and compare itself correctly on whatever operating system it runs on.