Python pathlib Module
In this page:
What is pathlib?
pathlib represents filesystem paths as objects rather than plain strings, giving you methods and operators (like / for joining) instead of manual string concatenation. This object-oriented approach reduces the cross-platform bugs that come from hand-building paths with hardcoded slashes.
Example: What is pathlib?
from pathlib import Path
p = Path("folder") / "file.txt"
print(p)
Extracting Path Properties
A Path object exposes ready-made properties for common path pieces: .parent for the containing directory, .name for the final filename component, and .suffix for the file extension. Pulling these out manually from a raw string would otherwise mean writing fragile string-splitting logic.
Example: Extracting Path Properties
from pathlib import Path
p = Path("/home/user/notes.txt")
print(p.parent)
print(p.name)
print(p.suffix)
Checking File Existence
Path.exists() checks whether the path actually points to something on disk before you attempt to open or read it, letting you fail gracefully with a clear message instead of hitting an unhandled FileNotFoundError deep inside your program's logic.
Example: Checking File Existence
from pathlib import Path
p = Path(".")
print(p.exists())
Reading and Writing Files
Path.read_text() and Path.write_text() (plus their _bytes counterparts) read or write a file's entire contents in a single call, without the boilerplate of manually opening a file handle, reading it, and remembering to close it afterward.
Example: Reading and Writing Files
from pathlib import Path
p = Path("notes.txt")
p.write_text("hello")
print(p.read_text())
Working with Directories
Path.mkdir() creates new directories (with a parents=True option to create intermediate ones as needed), and Path.iterdir() lets you loop over everything directly inside a directory, giving you Path objects back rather than plain filename strings.
Example: Working with Directories
from pathlib import Path
p = Path("demo_dir")
p.mkdir(exist_ok=True)
print(list(Path(".").iterdir())[:1])
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: