`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.
More on OS, filesystem, subprocess & CLIs
How do you read environment variables safely?BeginnerHow do you walk a directory tree and find files?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?IntermediateHow do you handle a failed command and show useful output?Intermediate