在 Python 3.5 和更高版本中,使用新的递归 **/ 功能:
configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)
当设置recursive 时,** 后跟路径分隔符匹配 0 个或多个子目录。
在早期的 Python 版本中,glob.glob() 无法递归列出子目录中的文件。
在这种情况下,我会使用 os.walk() 结合 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')]
这将递归遍历您的目录并将所有绝对路径名返回到匹配的.txt 文件。在这种特定的情况下,fnmatch.filter() 可能是矫枉过正,您也可以使用.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')]