stop using os.path, use pathlib
pathlib has been in the stdlib since Python 3.4. I kept typing os.path.join out of muscle memory for years after that. Last year I made myself stop. Should have done it sooner.
compare
import os
cfg = os.path.join(os.path.dirname(__file__), "..", "config", "settings.json")
with open(cfg) as f:
data = json.load(f)
from pathlib import Path
cfg = Path(__file__).parent.parent / "config" / "settings.json"
data = json.loads(cfg.read_text())
The / operator reads like a path. .parent.parent reads like what it is. .read_text() replaces the open-with-context dance when you just want the contents.
the five methods I use most
Path("a/b/c").exists()Path("dir").mkdir(parents=True, exist_ok=True)Path("file").write_text("hello")Path(".").glob("**/*.py")— walks the treePath("x.log").with_suffix(".gz")— returnsx.gzwithout rebuilding the string
when to still use os
Two cases: low-level file ops where you need flags (os.open with O_EXCL), or when a library you're calling demands a string. For the string case, pass str(path) and move on.
minor annoyance
Some stdlib functions don't accept Path objects until later Python versions. It's rare now but if you see a mysterious type error, that's the fix.