How to avoid certain directories when using os.walk?

Gabriel Genellina gagsl-py2 at
Sat Oct 31 07:10:34 CET 2009

En Fri, 30 Oct 2009 14:50:34 -0300, Sean DiZazzo <half.italian at>
> On Oct 29, 10:17 pm, Chris Rebert <c... at> wrote:
>> On Thu, Oct 29, 2009 at 9:53 PM, Peng Yu <pengyu... at> wrote:

>> > I don't see a way to avoid walking over directories of certain names
>> > with os.walk. For example, I don't want os.walk return files whose
>> > path include '/backup/'. Is there a way to do so? Otherwise, maybe I
>> > will have to make my own program. Thank you!
>> Read the docs! (
>> They even include a specific code example of how to skip unwanted
>> subdirectories.
> You will run into problems however if you want to delete from a tree
> while ignoring certain named directories.  Directories must be empty
> before they can be deleted, so you must use "topdown=False", but to
> prune a search you must use "topdown=True".  At least I think that was
> the problem I had with my deletion script a while back.

I'd say the problem is ill-defined in that case. You have to decide what
to do with those non-empty directories that are non-empty because you
explicitely skipped some subdirectories...

Gabriel Genellina

More information about the Python-list mailing list