gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:19:33 24 4
gpt4 key购买 nike

我想搜索文件,但包含 .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]

关于python-2.6 - 如何从 os.walk 中排除文件扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35293399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com