如何在使用os.walk()时排除目录?其他方法无效

1 投票
1 回答
736 浏览
提问于 2025-04-18 14:14

到目前为止,下面的代码一直很顽固:

for root,subdirs,files in os.walk(topDir):
    for fileName in files:
        if fileName.endswith(("0.tif","0.png")):
            images.update({fileName[:-5]:Image(fileName,origin)})
        elif fileName.endswith((".tif",".png")):
            try:
                images.update({fileName[:-4]:Image(fileName,picLocations[fileName[:-4]])})
            except:
                images.update({fileName[:-4]:Image(fileName,origin)})
        else:
            pass

我试着把前三行改成这样:

exclude = set(["faces","animations"])
for root,subdirs,files in os.walk(topDir):
    subdirs[:] = [d for d in subdirs if d not in exclude]

但是,这似乎并没有把不需要的东西过滤掉……我是不是做错了什么??

1 个回答

1

试试这个

exclude = set(["faces","animations"])
for root,subdirs,files in os.walk(topDir):
    subdirs[:] = [d for d in set(subdirs)-exclude]

撰写回答