python - 键在字典中时出现键错误

标签 python exif keyerror

只是试图从一堆照片的 EXIF 数据中提取一些纬度/经度信息,但代码会抛出 KeyError,即使稍后(成功)使用该键来打印特定坐标。

有问题的字典是“tags”——'GPS GPSLatitude''GPS GPSLongitude' 都是标签中的键。 key ();我已经检查了三次。

那么关于为什么 tags['GPS GPSLatitude']tags['GPS GPSLongitude'] 抛出关键错误的任何直觉?

import os
import exifread

output = dict()
output['name'] = []
output['lon'] = []
output['lat'] = []

for file in os.listdir(path):
    if file.endswith(".JPG"):
        full_path = path + file
        print (file) #check to ensure all files were found
        output['name'].append(file) #append photo name to dictionary
        f = open(full_path, 'rb') #open photo
        tags = exifread.process_file(f) #read exifdata
#       lon = tags['GPS GPSLongitude'] #this + next line = one method
#       output['lon'].append(lon)
#       output['lat'].append(tags['GPS GPSLatitude']) # = cleaner second method
        for tag in tags.keys():
            if tag in ('GPS GPSLongitude','GPS GPSLatitude'):
                print ("Key: %s, value %s" % (tag, tags[tag])) #successfully prints lat/lon coords with 'GPS GPSLongitude' and 'GPS GPSLatitude' as keys

更新:

这是 print (tags.keys()) 的输出——您会在其中看到 GPS GPSLatitudeGPS GPSLongitude。此外,已手动检查我正在使用的子集中的所有照片都有 GPS 数据。

dict_keys(['GPS GPSImgDirection', 'EXIF SceneType', 'MakerNote 标签 0x0006', 'GPS GPSDestBearing', 'Thumbnail XResolution', 'EXIF BrightnessValue', 'GPS GPSAltitude', 'GPS GPSLongitude', 'EXIF LensSpecification', 'GPS GPSAltitudeRef', 'GPS GPSSpeedRef', 'GPS GPSDestBearingRef', 'EXIF WhiteBalance', 'Thumbnail ResolutionUnit', 'EXIF FocalLengthIn35mmFilm', 'EXIF SceneCaptureType', 'Image Model', 'MakerNote Tag 0x0008' , 'Image Make', 'EXIF ShutterSpeedValue', 'MakerNote Tag 0x0007', 'EXIF ExifImageWidth', 'EXIF LensModel', 'Image YResolution', 'EXIF ComponentsConfiguration', 'Image GPSInfo', 'EXIF ISOSpeedRatings', 'EXIF ExposureMode ', 'EXIF Flash', 'EXIF FlashPixVersion', 'GPS GPSLatitudeRef', 'EXIF ExposureBiasValue', 'Thumbnail JPEGInterchangeFormatLength', 'Thumbnail Compression', 'Image YCbCrPositioning', 'EXIF MakerNote', 'EXIF FNumber', 'JPEGThumbnail' , 'MakerNote Tag 0x0001', 'EXIF ColorSpace', 'EXIF SubSecTimeDigitized', 'Thumbnail JPEGInterchangeFormat', 'MakerNote Tag 0x0004', 'EXIF SubjectArea', 'Image ResolutionUnit', 'EXIF SensingMethod', 'Image DateTime', 'Image Orientation', 'EXIF ExifVersion', 'Image ExifOffset', 'GPS GPSImgDirectionRef', 'MakerNote Tag 0x0014', '缩略图 YResolution', 'EXIF DateTimeOriginal', 'MakerNote Tag 0x0005', 'EXIF LensMake', 'EXIF DateTimeDigitized', 'MakerNote Tag 0x0003', 'GPS GPSTimeStamp', 'EXIF ExposureTime', 'GPS Tag 0x001F', 'EXIF SubSecTimeOriginal '、'GPS GPSLatitude'、'图像软件'、'EXIF ApertureValue'、'GPS GPSDate'、'EXIF ExposureProgram'、'GPS GPSSpeed'、'EXIF ExifImageLength'、'EXIF MeteringMode'、'GPS GPSLongitudeRef'、'EXIF FocalLength ', '图像 XResolution'])

回溯

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-14-949ba89a1248> in <module>()
     16 #        lon = tags["GPS GPSLongitude"]
     17 #        output['lon'].append(lon)
---> 18         output['lat'].append(tags['GPS GPSLatitude'])
     19         for tag in tags.keys():
     20             if tag in ('GPS GPSLongitude','GPS GPSLatitude'):

KeyError: 'GPS GPSLatitude'

照片链接:https://drive.google.com/a/cornell.edu/file/d/0B1DwcbbAH1yuTEs0cUhhODdlNnc/view

这张照片的打印语句输出

IMG_6680.JPG
Key: GPS GPSLongitude, value [76, 29, 353/20]
Key: GPS GPSLatitude, value [42, 26, 5069/100]

最佳答案

GPS GPSLatitudeGPS GPSLongitude 可能不会出现在所有标签字典中。

除了以 tags['GPS GPSLatitude']tags['GPS GPSLongitude'] 访问 key ,您还可以以 tags.get 访问这些 key ('GPS GPSLatitude') & tags.get('GPS GPSLongitude') 这将返回 None 而不是抛出错误,您可以在其中应用 if-else条件还用于验证这些 key 不存在的位置。

关于python - 键在字典中时出现键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37143664/

相关文章:

python - 匹配所有的正则表达式模式,并在找到特定单词时返回 null

c# - 在 C# 中从图像的 EXIF 获取 GPS 数据

python - KeyError : 0 的问题

python - 为什么我的代码不断抛出 KeyError?

python - 尝试子类化 Mechanize 浏览器并创建登录方法

Python 请求模块 - Google App Engine

c# - 在不丢失 EXIF 数据的情况下使用 .NET 调整图像大小

php - exif 在移动设备上使用 php 上传图片时剥离 GPS header ?

python pdfminer - KeyError 'AcroForm'

python - 有没有办法在Python中操作编号段落来删除某些不按顺序排列的段落?