pathlib Module Masterclass (Path Objects vs os.path)
1Concept
`pathlib.Path` provides an object-oriented API for filesystem path navigation, replacing `os.path`. The slash operator (`/`) joins paths intuitively, and methods like `.read_text()`, `.write_bytes()`, `.rglob()`, and `.stat()` offer clean, cross-platform filesystem operations.
2Architecture Diagram
path = Path("/var/log") / "services" / "api.log" ---> Intuitive slash operator joining!3Code Example
Python 3.12
from pathlib import Path
# Create path object (Cross-platform)
log_path = Path("build") / "reports" / "summary.json"
print(f"Path Representation: {log_path}")
print(f"Filename (name): {log_path.name}")
print(f"Extension (suffix): {log_path.suffix}")
print(f"Parent Directory: {log_path.parent}")
print(f"Is Absolute: {log_path.is_absolute()}")4Expected Output
Path Representation: build/reports/summary.json Filename (name): summary.json Extension (suffix): .json Parent Directory: build/reports Is Absolute: False
5Key Takeaways
- ✓The `/` operator on `Path` objects performs cross-platform path joining automatically.
- ✓Use `Path.rglob('*.py')` for recursive directory search.
- ✓`.read_text(encoding='utf-8')` handles open/read/close in a single clean expression.