如何从 os.walk 中排除文件扩展名

How to exclude files extension from os.walk

我想搜索文件,但包含 .txt 文件的文件除外。怎么做 ? 目前我的代码正在搜索扩展名为 .txt 的文件。如何做相反的事情?

src = raw_input("Enter source disk location: ")
src = os.path.abspath(src)
print "src--->:",src
for dir,dirs,_ in os.walk(src, topdown=True):

    file_path = glob.glob(os.path.join(dir,"*.txt"))

使用列表理解过滤文件:

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]