pathlib¶
| Difficulty | |
| Path(s) | Stdlib Deep Dives |
| Prereqs | Basic Python |
| Unlocks | caching, zipapp |
| Repo | pysprings/lightning-talks/pathlib |
Overview¶
Modern, object-oriented file path handling with Python's pathlib module (stdlib since Python 3.4). Replaces the older os.path functional approach with a cleaner API.
Key Concepts¶
Pathobjects replace string-based paths — use/operator instead ofos.path.join()- Cross-platform by default — no need to worry about path separators
- Built-in file operations —
Path.read_text(),Path.write_text(),Path.glob() - Rich attribute access —
.name,.suffix,.parent,.stem
The Code¶
pathlib/README.md — Full comparison of os.path vs pathlib
Before (os.path)¶
import os.path
fname = os.path.join(".", "test.py")
os.path.abspath("../../test.py")
os.path.basename("../../test.py")
os.path.splitext("test.py")
After (pathlib)¶
from pathlib import Path
fname = Path(".") / "test.py"
Path("../../test.py").resolve()
Path("../../test.py").name # "test.py"
# Glob returns a generator
all_python_files = Path(".").glob("**/*.py")
# Direct file I/O — no open() needed
Path("myfile.md").write_text("# Here's a title!")
Try It¶
- Open a Python REPL
- Try these one-liners:
- Challenge: Rewrite a script that uses
os.path.joinandos.path.existsto usepathlibinstead