How do I exclude directories when using os.walk()? Other methods haven't worked

柔情痞子 提交于 2019-12-14 02:23:40

问题


So far the following code has been nothing but stubborn:

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

I've tried making the first three lines read:

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

This, however, does not seem to filter out the unwanted items... am I doing something wrong??


回答1:


Trythis

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


来源:https://stackoverflow.com/questions/24883084/how-do-i-exclude-directories-when-using-os-walk-other-methods-havent-worked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!