5. Prefer pathlib over os.path

Prefer pathlib when working with filesystem paths. It composes operations more cleanly than string-based os.path code.

Object-style path composition tends to read more like filesystem manipulation and less like manual string assembly. It also keeps related operations on one type instead of spreading them across several os.path helper calls.

5.1. Don’t do this

1import os
2
3path = os.path.join('data', 'reports', 'summary.txt')
4if os.path.exists(path):
5    print(os.path.basename(path))

5.2. Do this

1from pathlib import Path
2
3path = Path('data') / 'reports' / 'summary.txt'
4if path.exists():
5    print(path.name)