Today I Learned 1 min read
TIL - Python's pathlib.Path Makes File Operations Readable and Composable
Replace verbose os.path.join() with Python's pathlib.Path. Use the / operator to join paths, making access operations readable and composable. Includes a working code example.
The old os.path.join(base, "subdir", "file.txt") is verbose and error-prone. pathlib.Path uses / operator for joining and has a clean API.
from pathlib import Path
base = Path("/data/projects")
config = base / "app" / "config.yaml"
config.parent.mkdir(parents=True, exist_ok=True)
config.write_text("key: value")
print(config.suffix) # .yaml
print(config.stem) # configpython