1

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?

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

should be os.walk not os.walkdir
@user248237dfsf, You're right. fixed that. Thank you for pointing that.