【问题标题】:How do I exclude directories when using os.walk()? Other methods haven't worked使用 os.walk() 时如何排除目录?其他方法没有奏效
【发布时间】:2014-09-13 00:28:56
【问题描述】:

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

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]

但是,这似乎并没有过滤掉不需要的项目......我做错了什么吗??

【问题讨论】:

  • subdirs[:] = 行前后放置一个print subdirs,看看会发生什么。
  • 您是否有机会使用 Windows 并以不同的方式命名您的实际目录,例如 FacesAnimations?那么你可能想做subdirs[:] = [d for d in subdirs if d.lower() not in exclude]
  • 是的,我之前和之后都将它们打印出来,而且它似乎工作正常。是的,我使用的是 Windows 8,但目录都是小写的。不过,我现在已经解决了大部分问题。
  • 我知道这很旧,但请查看我对类似问题的回答。 stackoverflow.com/a/51871627/1896134

标签: python python-2.7 os.walk


【解决方案1】:

试试这个

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

【讨论】:

  • 谢谢...不知道为什么这行得通,而其他方式并不诚实。现在我只需要弄清楚为什么它会错误地命名所有图像,即使它们是通过文件命名的。
  • 它产生 same 结果与subdirs[:] = [d for d in subdirs if d not in exclude] 除了订单。
猜你喜欢
  • 1970-01-01
  • 2022-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多