4. Essential Standard Library for Real Projects
Modern File & Directory Automation with pathlib
Replace clunky os.path string joining with Python's object-oriented pathlib.Path: join paths cleanly with /, search folders with glob/rglob, and automate file workflows safely.
- Build cross-platform file paths cleanly using Path and the / operator
- Inspect names, extensions, parents, and file stats without string slicing
- Search directory trees with .glob() and .rglob() and create folders safely
Older Python tutorials join file paths using os.path.join(base, "data", "report.csv"), split extensions by hand, and mix os.makedirs, glob.glob, and open(). Since Python 3.4, the standard library includes pathlib, which turns file paths into clean, cross-platform objects instead of fragile strings.
Why It Matters: Before vs After
Compare chaining os.path string helpers against pathlib.Path's unified object API:
# Before: nested os.path string functions scattered across modules
import os
base = os.path.dirname(os.path.abspath("data/raw/sales.csv"))
os.makedirs(os.path.join(base, "out"), exist_ok=True)
stem = os.path.splitext(os.path.basename("data/raw/sales.csv"))[0]
target = os.path.join(base, "out", f"{stem}.json")
# After: clean, chainable Path object methods and `/` operator
from pathlib import Path
src = Path("data/raw/sales.csv").resolve()
out_dir = src.parent / "out"
out_dir.mkdir(parents=True, exist_ok=True)
target = out_dir / src.with_suffix(".json").name1. Deep Mental Model: How Path & / Work
Path("reports/2026/sales_nov.csv")
Path splits folder, stem, and suffix cleanly across Windows, macOS, and Linux without fragile string slicing.
A Path object isn't a raw string—it stores normalized path segments internally and adapts to the operating system (PosixPath on macOS/Linux, WindowsPath on Windows):
- Operator overloading (
__truediv__): Writingbase_dir / "logs" / "app.log"works even if"logs"is astr, becausePathimplements__truediv__! (Note: at least the leftmost operand must be aPath, not two strings.) - Zero-guesswork anatomy:
Pathsplits every filename cleanly into parts without fragile.split(".")bugs on multi-dot files likearchive.tar.gzor dotfiles like.env:
from pathlib import Path
data_file = Path("projects") / "yadav-academy" / "logs" / "app.log"
print(data_file) # projects/yadav-academy/logs/app.log
print(data_file.name) # app.log (final filename + extension)
print(data_file.stem) # app (filename without final suffix)
print(data_file.suffix) # .log (final extension; suffixes -> ['.tar', '.gz'])
print(data_file.parent) # projects/yadav-academy/logs
print(data_file.parents[1])# projects/yadav-academy2. Reading, Writing & Creating Directories Safely
For quick config files, JSON outputs, or small text files, Path provides one-line helpers that open, read/write, and close the file handle automatically:
from pathlib import Path
out_dir = Path("reports/2026")
out_dir.mkdir(parents=True, exist_ok=True) # Creates missing parents, never crashes if it exists!
report = out_dir / "summary.txt"
report.write_text("Total sales: $420.00\n", encoding="utf-8")
print(report.read_text(encoding="utf-8"))(Always pass encoding="utf-8" explicitly—otherwise Windows defaults to legacy cp1252, crashing on emojis or accented characters!)
For multi-megabyte log or CSV files, stream line by line with .open() instead of loading everything into RAM with .read_text():
with report.open("r", encoding="utf-8") as fh:
for line in fh:
if "ERROR" in line:
print(line.strip())3. Searching & Inspecting Trees with .glob() and .rglob()
Need every .py or .csv file in a folder?
folder.glob("*.csv")searches only that immediate folder (returns a lazy generator ofPathobjects).folder.rglob("*.py")searches recursively through all subfolders too!
from pathlib import Path
for py_file in Path("src").rglob("*.py"):
if py_file.is_file():
print(py_file, py_file.stat().st_size, "bytes")Checking, Resolving & Relativizing Paths
In automation scripts, you frequently need to verify what a path points to or compute clean relative paths for logs and manifests:
p.exists()→Truefor any file, folder, or symlink; preferp.is_file()orp.is_dir()when you expect a specific kind.p.resolve()→ converts a relative path likePath("../logs/app.log")into its canonical absolute path (and resolves symlinks).p.relative_to(base)→ strips the leadingbaseprefix (e.g.,/app/src/utils.py→src/utils.py), raisingValueErrorifpisn't insidebase.Path.home()andPath.cwd()→ clean cross-platform entry points for the user's home folder and current working directory.
Decision Table & Common Pitfalls
| Task | Legacy os / shutil | Modern pathlib.Path |
|---|---|---|
| Join paths | os.path.join(a, b) | Path(a) / b |
| Swap extension | os.path.splitext(p)[0] + ".json" | p.with_suffix(".json") |
| Make nested folders | os.makedirs(d, exist_ok=True) | d.mkdir(parents=True, exist_ok=True) |
| Find files recursively | os.walk(...) + fnmatch | folder.rglob("*.py") |
| Current script folder | os.path.dirname(__file__) | Path(__file__).resolve().parent |
- Using
strmethods directly on aPath:path.endswith(".py")raisesAttributeError—usepath.suffix == ".py"instead! - Expecting
with_suffix(".json")to rename a file on disk:p.with_suffix(".json")only returns a newPathobject in memory; callp.rename(p.with_suffix(".json"))if you actually want to rename the file on disk.
Try It Yourself in the Playground
Pyodide includes a real virtual filesystem in your browser—let's create nested folders, write files, search with .rglob(), and inspect Path properties live:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Using Path, build a path Path("data/raw/sales_2026.csv"), print its stem ("sales_2026"), and produce a new path in data/processed/ named sales_2026.json using .with_suffix().
Quick Checkpoints
What do the flags in folder.mkdir(parents=True, exist_ok=True) guarantee?
What is the difference between path.glob('*.mdx') and path.rglob('*.mdx')?