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

时间:2014-07-22 09:01:35

标签: 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")):
            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 个答案:

答案 0 :(得分:1)

Trythis

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