[英]Trying to understand a KeyError
我有一个比较图像文件的代码,以检查一个目录中的图像是否与另一个目录中的任何图像匹配。 我不是在比较文件名,而是使用PIL
(Python 成像库)来实际比较图像。
我的代码返回一个目录名称不匹配的列表,这正是我所需要的。 我有 162 个带有图像的目录。 我的代码成功检查了 71 个目录并按预期返回了所需的输出。 然后,从目录 72 开始,我得到以下信息: KeyError: 'F:/162 pic sets ready/set72'
for all the rest of the directory。
这是我无法理解的部分:如果我将这些目录移动到其他位置,我仍然会遇到相同的错误,但是如果我将这些目录中的图像复制到另一个空目录并在我不知道的那些目录上运行代码得到错误。
from PIL import ImageChops
from PIL import Image
import math, operator
import os
path_images = ('C:/Users/Acer/Desktop/pics/')
list_to_match = []
for images in os.listdir(path_images):
images_to_match = Image.open(path_images + images)
list_to_match.append(images_to_match)
path_folders = ('F:/162 pic sets ready/')
d = {}
for dirpath, dirnames, filenames in os.walk(path_folders):
if 'Thumbs.db' not in filenames:
d[dirpath] = filenames
dict2 = {k: list(map(lambda x: (k+'/'+x ), v)) for k,v in d.items()}
c = 1
matches = []
folder_images_opened = []
while (c < 163):
for im in dict2['F:/162 pic sets ready/set%s' % c]:
test = Image.open(im)
folder_images_opened.append(test)
for images_to_find in list_to_match:
if images_to_find in folder_images_opened:
matches.append(c)
print ('Folders where we found a match:', c)
del folder_images_opened[:]
c = c+1
numbers = list(range(1,163))
numbers_filter = [i for i in numbers if i not in matches]
print ('Folders that does not have a match', numbers_filter)
这是完整的回溯:
KeyError Traceback (most recent call last)
<ipython-input-8-c663c9d71cf9> in <module>()
4
5 while (c < 80):
----> 6 for im in dict2['F:/162 pic sets ready/set%s' % c]:
7 test = Image.open(im)
8 folder_images_opened.append(test)
KeyError: 'F:/162 pic sets ready/set72'
你在做两个假设:
F:/162 pic sets ready/set72
确实存在,并且Thumbs.db
文件名。 如果任一假设不成立,则该路径不会在dict2
显示为键。
您可以简单地先测试密钥是否存在:
while (c < 163):
dirname = 'F:/162 pic sets ready/set%s' % c
if dirname not in dict2:
print('{} does not exist or has a Thumbs.db file'.format(dirname))
continue
for im in dict2[dirname]:
test = Image.open(im)
与其使用while
循环并期望所有setx
目录按顺序存在, setx
循环遍历dict2
的键; 你甚至可以对键进行排序:
for dirname in sorted(dict2):
directoryname = os.path.basename(dirname) # 'set<somenumber>'
我想你只是想 *skip Thumbs.db
,而不是跳过包含Thumbs.db
目录(一个很大的区别!)。 如果是这样,请在处理文件时测试文件名,而不是在处理目录时:
for im in dict2['F:/162 pic sets ready/set%s' % c]:
if os.path.basename(im) == 'Thumbs.db':
continue
test = Image.open(im)
folder_images_opened.append(test)
并删除if 'Thumbs.db' not in filenames:
test 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.