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?

Était-ce utile?

La solution

Use 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]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top