【发布时间】: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 并以不同的方式命名您的实际目录,例如
Faces或Animations?那么你可能想做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