Iterating through directories with Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Directory iteration is a core task in automation, data engineering, and build tooling. Python offers multiple APIs, each with tradeoffs in readability, performance, and metadata access. Choosing the right approach helps you write faster and more maintainable file traversal code.
Basic Traversal with os.walk
os.walk is a reliable recursive iterator that yields directory paths, subdirectory names, and file names.
This is often the best default for recursive processing.
Modern Path Handling with pathlib
pathlib gives an object-oriented API and cleaner path operations.
Path objects improve readability and reduce path-join mistakes.
Fast Non-Recursive Scanning with os.scandir
When you only need one directory level and file metadata, os.scandir is fast and efficient.
It avoids some extra system calls compared with basic list and stat loops.
Practical Filtered Traversal
Real workflows usually need include and exclude rules. Keep those rules explicit.
A clear filter strategy prevents hidden bugs and slow scans.
Error Handling for Robust Scripts
File traversal can fail on permission errors, deleted files, or broken links. Handle exceptions where they occur and log useful context.
This keeps long-running scans resilient instead of failing on one problematic path.
Build a Reusable Traversal Utility
For repeatable tooling, wrap traversal logic in a utility function that accepts filters and callback behavior.
This keeps file discovery logic consistent across scripts.
Parallel Processing Pattern
Traversal is often only the first step. If per-file work is expensive, process files with a bounded worker pool.
Bounded concurrency improves throughput while avoiding uncontrolled system load.
Make Traversal Deterministic
When script output is compared in CI, deterministic ordering matters. Sort discovered paths before processing.
Stable ordering makes tests and diffs easier to review.
Consistent traversal utilities also simplify testing and cross-platform maintenance for automation scripts.
Common Pitfalls
- Building paths with manual string concatenation.
- Scanning huge trees without directory filters.
- Assuming every traversed path is readable.
- Ignoring symbolic links and creating unexpected traversal behavior.
Summary
- Use
os.walkfor straightforward recursive directory traversal. - Use
pathlibfor cleaner path handling, globbing, and readable path composition. - Use
os.scandirfor fast local directory scans. - Add explicit filters, pruning, and robust error handling for production scripts.
Related reading
- Java Virtual Machine vs. Python Interpreter parlance?
- Java Virtual Machine vs. Python Interpreter parlance?
- Java's Mahout equivalent in Python
- Javascript equivalent of Python's zip function
- joblib.load __main__ AttributeError
- Join a string using delimiters
- join list of lists in python
- Joining columns in pandas incorrectly
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.