Here's a sample of my directory structure: https://pastebin.com/XimFQdS7
Assuming thousands of subdirectories and files, a recursive search for all files with 'prj' extension could take several seconds.
Assuming I knew that a project dir would only contain one 'pjt' file, I could discard all its subdirs from my search, saving a substantial amount of time.
This would be the desired output for the above structure:
[
'root/dir1/dirA/',
'root/dir1/dirB/',
'root/dir2/',
'root/dir3/dirA/dirX/',
'root/dir3/dirA/dirY/'
]
This is my current search code:
def getSubDirectoriesContainingFileType(root, extension):
os.chdir(root)
fileFormat = '**/*.{}'.format(extension)
files = glob.glob(fileFormat, recursive = True)
matchingDirs = [os.path.dirname(os.path.abspath(file)) for file in files]
return matchingDirs
I've used glob as I found it to be a bit faster than os.walk() but I think in order to implement the algorithm I'm talking about above I'd have to go back to os.walk().
The idea for the algorithm is:
def searchDirs(root):
dirs = []
for dir in rootDirs:
search for file with ext
if found:
append dir to dirs
else:
append searchDirs(dir) to dirs
return dirs
While I could clumsily implement this algorithm, I'm wondering if any of the built-in libraries already provide this functionality, so as to ensure maximum efficiency.