Is there an alternative to os.walk?

Ant antroy at gmail.com
Sun Oct 8 02:51:33 EDT 2006


The idiomatic way of doing the tree traversal is:

def search(a_dir):
   valid_dirs = []
   for dirpath, dirnames, filenames in os.walk(a_dir):
       if dirtest(filenames):
           valid_dirs.append(dirpath)
   return valid_dirs

Also since you are given a list of filenames in the directory, then why
not just check the list of those files for your test files:

def dirtest(filenames):
   testfiles = ['a','b','c']
   for f in testfiles:
       if not f in filenames:
           return False
   return False

You'd have to test this to see if it made a difference in performance,
but it makes for more readable code




More information about the Python-list mailing list