collect all directories matching criteria from directory tree in python
Question: How can I collect all directories that match a criteria (like 'contain a file
named foo.txt') recursively from a directory tree? something like:

    
    
    def has_my_file(d):
       return ('foo.txt' in os.listdir(d))
    
    walk_tree(dirname, criterion=has_my_file)
    

for the tree:

    
    
    home/
      bob/
        foo.txt
      sally/
        mike/
          foo.txt
    

`walk_tree` should return:

    
    
    ['home/bob/', 'home/sally/mike']
    

is there such a function in python libraries?


Answer: Use [`os.walk`](http://docs.python.org/3/library/os.html#os.walk):

    
    
    import os
    
    result = []
    for parent, ds, fs in os.walk(dirname):
        if 'foo.txt' in fs:
            result.append(parent)
    

Using list comprehension:

    
    
    result = [parent for parent, ds, fs in os.walk(dirname) if 'foo.txt' in fs]
    

