ReviseAlgo Logo

File Handling

pathlib Module

Modern, object-oriented filesystem path manipulation — path construction, file operations, directory traversal, and glob patterns using the pathlib module.

Interview: pathlib is the modern standard for path handling in Python 3 — interviewers prefer it over os.path for cleaner, cross-platform code.

Last Updated: June 12, 2026 10 min read

The pathlib module (Python 3.4+) provides an object-oriented approach to filesystem paths, replacing the older os.path string-based functions. It handles cross-platform path separators automatically and offers a clean, intuitive API for common file operations.

Path Objects

  • Path() — current directory, Path("folder", "file.txt") — construct from parts
  • Path("folder") / "file.txt" — the / operator joins paths cleanly
  • Path.home() — user home directory, Path.cwd() — current working directory
  • Path objects are immutable and hashable — can be used as dict keys

Path Properties and Methods

  • .name — filename, .stem — name without extension, .suffix — extension
  • .parent — parent directory, .parts — tuple of path components
  • .exists(), .is_file(), .is_dir() — check path properties
  • .read_text(), .write_text(), .read_bytes(), .write_bytes() — simple file I/O
  • .mkdir(parents=True, exist_ok=True) — create directory with all parents

Directory Traversal and Glob

  • .iterdir() — iterate over directory contents
  • .glob("*.py") — find files matching a pattern (non-recursive)
  • .rglob("*.py") — recursive glob, searches all subdirectories
  • .resolve() — returns absolute path, resolving symlinks

Interview Insight

Prefer pathlib over os.path in modern Python code. Know how to use the / operator for path joining, and glob/rglob for file discovery. Be able to explain why pathlib is better than os.path (type safety, cross-platform, cleaner API).

Use Cases

Cross-platform file paths — automatic handling of / vs \ separators

Project scaffolding — creating directory structures programmatically

File discovery — finding files by pattern with glob/rglob

Configuration management — locating and reading config files

Build tools — processing source files in project directories

Common Mistakes

Using string concatenation for paths instead of Path / operator — breaks on Windows

Not specifying encoding in read_text/write_text — may fail on non-ASCII characters

Forgetting parents=True in mkdir — fails if parent directories don't exist

Using os.path functions on Path objects — use Path methods instead for consistency

Not using resolve() when you need absolute paths — relative paths can cause confusion