What is pathlib, and why is it preferred over os.path?
pathlib represents file paths as objects, so you can join them with /, read their parts and read or write files through methods. It is more readable than string-based os.path calls and handles Windows and Linux separators for you.
Explain it simply
With os.path a path is just a string, and you use separate helper functions to work on it. With pathlib a path is a small object that knows how to answer questions about itself: "what is your name?", "do you exist?", "what is inside you?".
Example
from pathlib import Path
base = Path("reports")
file = base / "2026" / "summary.txt"
print(file) # Output: reports/2026/summary.txt
print(file.name) # Output: summary.txt
print(file.stem) # Output: summary
print(file.suffix) # Output: .txt
print(file.parent) # Output: reports/2026
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text("done", encoding="utf-8")
print(file.read_text(encoding="utf-8")) # Output: done
print(file.exists()) # Output: True
for p in base.rglob("*.txt"):
print(p.name) # Output: summary.txtThe / operator on paths is the standout feature: no manual separators, no os.path.join. On Windows the same code prints backslashes.
What to say in the interview
"pathlib gives an object-oriented path API: Path joining with /, .name, .suffix, .parent, .exists(), read_text and glob. It is more readable, portable across operating systems, and part of the standard library since 3.4. os.path still works and appears in older code."