Excluding directories in os.walk
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
When using os.walk, the correct way to exclude directories is to modify the dirnames list in place while walking top-down. If you only filter results after traversal, Python may still recurse into directories you meant to skip, which wastes time and defeats the purpose of exclusion.
How os.walk decides where to recurse
When topdown=True, os.walk yields three values for each directory:
- '
dirpath' - '
dirnames' - '
filenames'
The important detail is that dirnames is not just informational. It is the list Python uses to decide which child directories to visit next.
The slice assignment is crucial.
Why dirnames[:] = ... matters
This works:
This does not control recursion the same way:
The second version only rebinds the local variable. It does not mutate the original list that os.walk is using internally.
That is the most important detail in this whole topic.
Exact names versus patterns
If exact directory names are not enough, use pattern matching.
This is useful when generated folders follow naming patterns rather than one fixed name.
Excluding by full path
Sometimes the directory name alone is not enough because the same name may appear in places you do want to visit.
This gives you much more precise control.
A reusable helper
This keeps the exclusion logic consistent across scripts instead of re-implementing it each time.
Why filtering afterward is worse
If you walk every directory and only later ignore paths you do not care about, you still pay the recursion cost. That can be slow in repositories with large dependency trees, build outputs, or virtual environments.
In other words, post-filtering hides unwanted results from your output, but it does not prevent the wasted traversal work that caused the slowdown in the first place.
So the rule is simple: prune recursion early rather than post-filtering later.
Common Pitfalls
A common mistake is reassigning dirnames instead of mutating it in place.
That tiny-looking difference is exactly why many first attempts appear correct in code review but still recurse into every directory at runtime.
Another mistake is using topdown=False, which removes the opportunity to prune child recursion before it happens.
A third mistake is filtering file results afterward and assuming excluded directories were never visited.
Summary
- Exclude directories by modifying
dirnamesin place. - Use
topdown=Trueso recursion can be pruned before descending. - Use exact names, patterns, or full paths depending on the use case.
- Do not just rebind
dirnames; mutate it with slice assignment. - Early pruning is more efficient than filtering after traversal.
- Mutate
dirnamesin place if you want recursion itself to change.

