pathlib.Path offers object-oriented paths—prefer it over string concatenation for cross-platform code. The os module provides lower-level process and filesystem utilities.
pathlib basics
from pathlib import Path
root = Path(".")
for py_file in root.glob("*.py"):
print(py_file.name)
joined = Path("data") / "logs" / "app.log"
os module snippets
import os
print(os.getcwd())
print(os.environ.get("HOME", "unknown"))
In the playground, path globs may be limited—practice full directory walks locally.
Important interview questions and answers
- Q: Path vs os.path?
A: pathlib is higher-level and composable with/; os.path is legacy string-based but still common in older code. - Q: Absolute vs resolve()?
A:resolve()makes absolute and resolves symlinks where possible.
Self-check
- How join path parts with pathlib?
- What does Path.glob do?
Tip: Prefer Path over string paths—Path("data") / "file.txt" is cross-platform.
Interview prep
- Path vs os.path?
pathlib object-oriented and composable; os.path string-based legacy API.
- Path.glob?
Yield paths matching pattern—like shell glob in Python.