🐍 Python Intermediate

What is Python's pathlib module?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

The pathlib module (Python 3.4+) provides an object-oriented interface to filesystem paths, replacing the older os.path. Create a path: from pathlib import Path; p = Path("/home/user/docs"). Join paths: p / "file.txt" (using the / operator). Read/write text: p.read_text(), p.write_text("content"). Read/write bytes: p.read_bytes(), p.write_bytes(). Inspect: p.exists(), p.is_file(), p.is_dir(), p.suffix (extension), p.stem (name without extension), p.name (filename), p.parent. List contents: list(p.iterdir()), list(p.glob("*.py")), list(p.rglob("*.py")). Create: p.mkdir(parents=True, exist_ok=True). Delete: p.unlink() (file), p.rmdir() (empty dir). Current directory: Path.cwd().

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last Python project, I used this when...' immediately makes your answer more credible and memorable.