Limitation of os.walk

Tim Chase python.list at tim.thechases.com
Tue May 11 17:53:48 EDT 2010


On 05/11/2010 02:49 PM, kj wrote:
> I want implement a function that walks through a directory tree
> and performs an analsysis of all the subdirectories found.  The
> task has two essential requirements that, AFAICT, make it impossible
> to use os.walk for this:
>
> 1. I need to be able to prune certain directories from being visited.
>
> 2. The analysis on each directory can be performed only after it
>     has been performed on all its subdirectories.
>
> Unless I'm missing something, to do (1), os.walk must be run with
> topdown=True, whereas to do (2) it must be run with topdown=False.

I don't think there's a way to coerce os.walk into doing what you 
want.  That said, the core source for os.walk() is a whole 23 
lines of code, it's easy enough to just clone it and add what you 
need...

> PS: I never understood why os.walk does not support hooks for key
> events during such a tree traversal.

including hooks for calling pre/post hooks.

-tkc





More information about the Python-list mailing list