pathlib for filesystem paths
Overview
`pathlib.Path` is the modern, object-oriented way to handle filesystem paths — replacing string juggling and most of `os.path`. You build paths with the `/` operator and query or act on them with methods. from pathlib import Path data = Path('data') csv = data / 'reports' / 'q1.csv' # OS-correct separators csv.suffix # '.csv' csv.stem # 'q1' csv.name # 'q1.csv' csv.parent # Path('data/reports') csv.exists() # bool Path objects also read and write directly (`csv.read_text(encoding='utf-8')`, `p.write_text(...)`), list directories (`Path('.').iterdir()`), glob (`Path('.').glob('**/*.py')`), and create folders (`p.mkdir(parents=True, exist_ok=True)`). Because `/` inserts the correct separator per OS, the same code works on Windows and Linux.
String path manipulation ('dir' + '/' + name) is error-prone and breaks across operating systems. `pathlib` makes path logic readable, cross-platform, and less bug-prone, and it's the idiom modern Python code and libraries expect.
Where used: Locating config and data files, Walking directory trees, Cross-platform CLI tools and scripts
Why learn this
- Cross-platform path handling that just works on both Windows and Unix without manual separator juggling.
- It's the modern idiom — most current libraries and codebases pass and expect `Path` objects.
Code walkthrough
from pathlib import Path
p = Path('project') / 'src' / 'main.py'
print(p.name)
print(p.stem)
print(p.suffix)
print(p.parent)
Focus: p.parent (everything above the file: Path('project/src'))
Common mistakes
- Building paths with string concatenation: `base + '/' + name` hardcodes the separator and breaks on Windows (and doubles slashes). Use `base / name` — the `/` operator inserts the OS-correct separator.
- Confusing .name, .stem, and .suffix: For `q1.csv`: `.name` is 'q1.csv', `.stem` is 'q1' (no extension), `.suffix` is '.csv'. Mixing them up leads to filenames with or without the extension where you didn't expect.
- Forgetting exist_ok / parents on mkdir: `p.mkdir()` raises if the directory already exists or if a parent is missing. Use `p.mkdir(parents=True, exist_ok=True)` for the common 'ensure this folder exists' intent.
Glossary
- Path object
- An object representing a filesystem path with methods and operators for manipulating it. Example: `Path('data') / 'in.csv'`.
Recall questions
- How do you join a directory and a filename with pathlib, and why is it better than string concatenation?
- For `Path('report.tar.gz')`, what are `.suffix`, `.stem`, and `.name`?
- How do you recursively find all `.py` files under a directory with pathlib?
Understanding checks
What does this print?
c .txt
`.stem` is the final component without its extension ('c'), and `.suffix` is the extension including the dot ('.txt'). They're printed space-separated.
You need code that joins a base directory and filename and runs correctly on both Windows and Linux. Which approach do you choose: `base + '/' + name`, or `Path(base) / name`?
`Path(base) / name`.
The `/` operator on Path inserts the platform-correct separator (`\` on Windows, `/` on Unix), whereas hardcoding '/' in a concatenation produces wrong or mixed separators on Windows.
Practice tasks
Build and inspect a path
Using pathlib and the `/` operator, build the path `output/data/results.json` starting from `Path('output')`. Print its `.parent`, `.stem`, and `.suffix`.
Continue learning
Previous: Reading and writing files with open()