Python pathlib Module
In this page:
from pathlib import Path
path = Path("folder/file_name")
path.exists()
path.read_text()
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" # / joins path segments
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) # containing directory
print(p.name) # final filename component
print(p.suffix) # file extension
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()) # checks the path is actually on disk before using it
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") # writes without manually opening/closing a file
print(p.read_text()) # reads the whole file in one call
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) # creates the directory, no error if it already exists
print(list(Path(".").iterdir())[:1]) # lists entries as Path objects
- Adding paths with
+, whenPath("a") / "b"is the correct way to join them. - Forgetting that a
Pathis not a string, so functions that need text may requirestr(path). - Calling
read_text()on a missing file, which raisesFileNotFoundError; checkpath.exists()first.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: