In Python 3.5 and later, use the new recursive **/ functionality:
configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)
When recursive set, ** followed by a path separator, matches 0 or more subdirectories.
In earlier versions of Python, glob.glob() could not recursively list files in subdirectories.
In this case, I would use os.walk() combination with fnmatch.filter() :
import os import fnmatch path = 'C:/Users/sam/Desktop/file1' configfiles = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(path) for f in fnmatch.filter(files, '*.txt')]
This will recursively navigate your directories and return all absolute paths to the corresponding .txt files. In this particular case, fnmatch.filter() might be redundant, you can also use .endswith() :
import os path = 'C:/Users/sam/Desktop/file1' configfiles = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(path) for f in files if f.endswith('.txt')]
Martijn Pieters Feb 10 '13 at 13:31
source share