pathlib is a standard library module (introduced in Python 3.4) that provides an object-oriented interface to filesystem paths. Instead of manipulating path strings with os.path.join(), os.path.exists(), and os.path.splitext(), you work with Path objects that support operators and methods: Path('data') / 'file.csv' joins paths, path.exists() checks existence, and path.suffix returns the extension.
The Path class provides methods for reading and writing (path.read_text(), path.write_text(), path.read_bytes()), directory operations (path.mkdir(), path.iterdir(), path.glob('*.py')), file metadata (path.stat(), path.is_file(), path.is_dir()), and path manipulation (path.parent, path.name, path.stem, path.with_suffix('.txt')). It automatically handles platform differences (forward slashes on Unix, backslashes on Windows).
pathlib has largely superseded os.path for new code. Most standard library and third-party functions now accept Path objects alongside strings. The Path class is particularly useful in combination with f-strings and context managers: data = (Path.home() / '.config' / 'app' / 'settings.json').read_text(). It makes path operations more readable, less error-prone, and more composable than string manipulation.
Related terms: Module
Discussed in:
- Chapter 8: Files and Input/Output — Paths with pathlib