Python pathlib
Learn to navigate and manipulate file system paths the Pythonic way: using objects instead of fragile strings.
What Is a Path?
A path is the address of a file or folder on your computer. It tells the operating system exactly where to look: which drive, which folders, and which file name.
The Old Way: String Paths
Before pathlib, Python developers used raw strings and the os.path module. This works, but it is clunky, error-prone, and looks different on Windows versus Mac/Linux.
Enter pathlib
pathlib is a built-in Python module (since Python 3.4) that treats paths as objects instead of strings. This means paths have methods and properties you can call directly: no more juggling os.path functions.
The Core Class: Path
Strings vs Path Objects
| String + os.path | pathlib.Path | |
|---|---|---|
| Join paths | os.path.join(a, b) | a / b |
| Get filename | os.path.basename(p) | p.name |
| Get extension | os.path.splitext(p)[1] | p.suffix |
| Check exists | os.path.exists(p) | p.exists() |
| Read file | open(p).read() | p.read_text() |
| Cross-platform | Manual care needed | Automatic |
Anatomy of a Path Object
How to Apply pathlib
Essential Properties
Joining Paths with /
The / operator is pathlib's signature move. It creates a new Path by appending segments, automatically using the correct separator for your OS.
Useful Methods
Example 1: Inspecting a Path
Example 2: Building and Checking
Example 3: Globbing for Files
Common Mistakes
Question 1 of 5
What does the / operator do when used between two Path objects (or a Path and a string)?
Question 2 of 5
Given p = Path("/data/logs/error.log"), what does p.stem return?
Question 3 of 5
Which method would you use to find all .csv files in a directory and its subdirectories?
Question 4 of 5
What happens if you call p.mkdir() and a parent directory in the path does not exist?
Question 5 of 5
Which of the following is a key advantage of pathlib over os.path?