Sometimes, we want to do a recursive sub-folder search and return files in a list with Python.
In this article, we’ll look at how to do a recursive sub-folder search and return files in a list with Python.
How to do a recursive sub-folder search and return files in a list with Python?
To do a recursive sub-folder search and return files in a list with Python, we can use glob.
For instance, we write
import os
from glob import glob
result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.txt'))]
to call os.walk to get the directories in PATH.
And then we loop through then files in y to get the files with the txt extension in the directory with
glob(os.path.join(x[0], '*.txt')
os.walk will recursively traverse child directories in PATH.
Conclusion
To do a recursive sub-folder search and return files in a list with Python, we can use glob.