Filesystem Automation with pathlib
Standard Library
pathlib Cheat Sheet
`pathlib.Path` gives you cross-platform path handling, globbing, and file reads/writes in one interface.
Paths
from pathlib import Path
root = Path(__file__).parent
reports = root / 'reports' / '2024'
reports.mkdir(parents=True, exist_ok=True)
- Use
/operator to join segments. Path.home()returns the user directory.
Operations
| Task | Snippet |
|---|---|
| Read text | Path('notes.txt').read_text() |
| Write text | Path('notes.txt').write_text('Hello') |
| Iterate files | for p in root.glob('*.log'): |
| Check existence | path.exists() |
| File metadata | path.stat().st_size |