使用列表理解过滤您的文件:
for dir, dirs, files in os.walk(src):
files = [os.path.join(dir, f) for f in files if not f.endswith('.txt')]
我删除了topdown=True 参数;这是默认设置。
不要将glob.glob() 与os.walk() 结合使用;这两种方法都在操作系统中查询目录中的文件名。您已经在os.walk()的每次迭代的第三个值中拥有这些文件名。
如果要跳过整个目录,使用any() function查看是否有匹配的文件,然后使用continue忽略此目录:
for dir, dirs, files in os.walk(src):
if any(f.endswith('.txt') for f in files):
continue # ignore this directory
# do something with the files here, there are no .txt files.
files = [os.path.join(dir, f) for f in files]
如果您想忽略此目录及其所有后代,请也使用切片分配清除 dirs 变量:
for dir, dirs, files in os.walk(src):
if any(f.endswith('.txt') for f in files):
dirs[:] = [] # do not recurse into subdirectories
continue # ignore this directory
# do something with the files here, there are no .txt files.
files = [os.path.join(dir, f) for f in files]