简体   繁体   English

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

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

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?? 但是,这似乎并没有过滤掉不需要的项目...我做错了吗?

Trythis 尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM