tkbx
tkbx

Reputation: 16275

Search directory for a directory with certain files?

I'd like to search a folder recursively for folders containing files names "x.txt" and "y.txt". For example, if it's given /path/to/folder, and /path/to/folder/one/two/three/four/x.txt and /path/to/folder/one/two/three/four/y.txt exist, it should return a list with the item "/path/fo/folder/one/two/three/four". If multiple folders within the given folder satisfy the conditions, it should list them all. Could this be done with a simple loop, or is it more complex?

Upvotes: 0

Views: 103

Answers (1)

Steve Mayne
Steve Mayne

Reputation: 22818

os.walk does the hard work of recursively iterating over a directory structure for you:

import os

find = ['x.txt', 'y.txt']

found_dirs = []
for root, dirs, files in os.walk('/path/to/folder'):
    if any(filename in files for filename in find):
        found_dirs.append(root)

#found_dirs now contains all of the directories which matched

Upvotes: 2

Related Questions