Skip to main content

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

TaskSnippet
Read textPath('notes.txt').read_text()
Write textPath('notes.txt').write_text('Hello')
Iterate filesfor p in root.glob('*.log'):
Check existencepath.exists()
File metadatapath.stat().st_size

Next up in your learning path