pathlib for filesystem paths

RoadmapsPython

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

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

Glossary

Path object
An object representing a filesystem path with methods and operators for manipulating it. Example: `Path('data') / 'in.csv'`.

Recall questions

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()

Return to Python Roadmap