Python 使用os.walk()时如何排除目录?其他方法';不起作用

Python 使用os.walk()时如何排除目录?其他方法';不起作用,python,python-2.7,os.walk,Python,Python 2.7,Os.walk,到目前为止,以下代码非常顽固: 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")):

到目前为止,以下代码非常顽固:

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]
然而,这似乎并没有过滤掉不需要的项目。。。我做错什么了吗?

试试看

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

子目录[:]=
行前后放置一个
打印子目录
,看看会发生什么。您是否有机会使用Windows并以不同的方式命名实际目录,例如
动画
?然后您可能需要执行
细分曲面[:]=[d表示细分曲面中的d,如果d.lower()不在exclude中]
。是的,我在之前和之后都将它们打印出来了,并且它似乎工作正常。是的,我使用的是Windows8,但是目录都是小写的。不过我现在已经把大部分问题都解决了。我知道这是一个老问题,但请检查我对一个类似问题的回答。谢谢老实说,我不知道为什么其他方法不起作用。现在我只需要弄清楚为什么它会错误地命名所有图像,即使它们是通过文件命名的。它会产生与
subdirs[:]=[d对于subdirs中的d,如果d不在exclude中]
相同的结果,除了顺序之外。