在Python 3.5及更高版本中,使用新的递归
**/功能:
configfiles = glob.glob('C:/Users/sam/Desktop/file1*.txt', recursive=True)当
recursive被设置时,
**随后是路径分隔匹配0或多个子目录。
在早期的Python版本中,
glob.glob()无法递归列出子目录中的文件。
在这种情况下,我将改用
os.walk()结合
fnmatch.filter():
import osimport fnmatchpath = '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()可能是矫kill过正,您也可以使用
.endswith()测试:
import ospath = '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')]


