Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

`os.path` vs `pathlib`: which do you use and why?

BeginnerConceptOS, filesystem, subprocess & CLIs
Answer

pathlib.Path is the modern, object-oriented API and what we use in new code. Paths compose with /, and methods cover most file tasks:

from pathlib import Path
cfg = Path.home() / ".aws" / "config"
cfg.exists(); cfg.read_text(encoding="utf-8")
for p in Path("/var/log/app").glob("*.log"): print(p.name, p.stat().st_size)
Path("reports").mkdir(parents=True, exist_ok=True)
p.suffix, p.stem, p.parent, p.with_suffix(".bak")

os.path still works and you will read plenty of it. Most standard library functions accept Path objects directly.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs