pathlib
Path(...) gives you an object that knows its name, suffix and parent, joins with /, and reads, writes and lists files itself. Pure paths do the string arithmetic without ever touching the disk.
from pathlib import Path from pathlib import PurePosixPath, PureWindowsPath import pathlib
Demo
from pathlib import PurePosixPath p = PurePosixPath('/home/ada/report.pdf') (p.parent, p.name, p.stem, p.suffix)
PurePosixPath normalises as it parses: repeated slashes and "." segments disappear and a trailing slash is dropped, but ".." is kept because removing it would need the file system. stem and suffix only split off the LAST extension, so site.tar.gz has the stem site.tar, and a name that starts with a dot (.bashrc) has no suffix at all. In the glob tab, results come back in whatever order the OS lists them, so the snippet sorts them.
Members
Common patterns
from pathlib import Path HERE = Path(__file__).resolve().parent config = HERE / 'config' / 'settings.toml'
from pathlib import Path p = Path('notes.txt') p.write_text('hello\n', encoding='utf-8') text = p.read_text(encoding='utf-8')
from pathlib import Path for csv_file in sorted(Path('data').rglob('*.csv')): print(csv_file.stem, csv_file.stat().st_size)
from pathlib import Path out = Path('build') / 'reports' out.mkdir(parents=True, exist_ok=True)
from pathlib import Path src = Path('photos/cat.jpeg') dst = src.with_suffix('.webp')
Examples
Pitfalls
base = 'data/' base + '/' + 'raw.csv'
from pathlib import PurePosixPath PurePosixPath('data/') / 'raw.csv'
from pathlib import PurePosixPath PurePosixPath('/srv/uploads') / '/etc/passwd'
from pathlib import PurePosixPath base = PurePosixPath('/srv/uploads') (base / '/etc/passwd').is_relative_to(base)
from pathlib import PurePosixPath PurePosixPath('reports/../secrets.txt')
from pathlib import Path Path('reports').mkdir() (Path('reports/../secrets.txt').resolve() == Path('secrets.txt').resolve())
When to use
- Any new code that builds, inspects or walks file paths
- Reading or writing small files in one call (read_text / write_text)
- Finding files by pattern (glob / rglob) and walking trees (walk)
- Manipulating Windows or POSIX paths on any OS (PureWindowsPath / PurePosixPath)
- Copying and moving whole trees → shutil (copytree, move, rmtree); Path.copy / move only arrive in 3.14
- Temporary files and folders → tempfile
- URLs → urllib.parse (as_uri / from_uri only handle file: URIs)
Notes
FAQ
pathlib for new code: a Path carries its own name, suffix, parent and I/O methods, joins with /, and is accepted everywhere a path string is (open, os, shutil). os.path remains fine in old code — the Notes table lists the pathlib equivalent of each os.path function.