Interview Q&A / Python

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What is pathlib, and why is it preferred over os.path?

SHORT ANSWER

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

python
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.txt

The / 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."

#python#file-io#pathlib

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.