Search for Files in Directories Recursively in Python
Let’s say you want to search for files in a directory tree of files and directories. And suppose you want to search for all .zip files. You can do this from within Python by looping through the folders and trying to find files that match the *.zip wildcard pattern.
Here is some code I copied from this page that illustrates how to do it:
import os, fnmatch def locate(pattern, root=os.curdir): for path, dirs, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename)
Note that this function uses the yield keyword, which turns this method into a generator. I wasn’t sure off hand how to access the results of this method, but it turns out you can iterate over it (for example, using a for loop).
for x in locate("*.zip", "C:\\Temp"): print x
If you didn’t want to use yield, you could do it this way:
import os, fnmatch def locate(pattern, root=os.curdir): matches = [] for path, dirs, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): matches.append(os.path.join(path, filename)) return matches
This would return a list.
See also this post that explains how to do this in a single folder (not recursively).