Limitation of os.walk

Terry Reedy tjreedy at udel.edu
Tue May 11 22:07:35 EDT 2010


On 5/11/2010 3: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.
>
> Is there a work around that I'm missing?

(I was going to say, 'Copy the code from os.py and revise to suit' -- 
but I see this has been posted since I wrote it ;-)

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

Either 1) it is intentionally simple, with the expectation that people 
would write there own code for more complicated uses or 2) no one has 
submitted a 'full-featured' version or 3) both.

If os.walk were rewritten, it should be as an iterator (generator). 
Directory entry and exit functions could still be added as params.

Terry Jan Reedy







More information about the Python-list mailing list