Exclude Directories from os.walk

Tim Golden mail at timgolden.me.uk
Tue Oct 21 12:16:21 EDT 2008


D wrote:
> Hello,
> 
> How can one exclude a directory (and all its subdirectories) when
> running os.walk()?

Just remove it from the dirnames yielded:

<code>
import os

for dirpath, dirnames, filenames in os.walk ("c:/temp"):
  print dirpath
  if "archive" in dirnames:
    dirnames.remove ("archive")

</code>

TJG



More information about the Python-list mailing list