密钥在字典中时的密钥错误

时间:2016-05-10 16:02:23

标签: python exif keyerror

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

有问题的词典是“tags” - 'GPS GPSLatitude''GPS GPSLongitude'都是tags.keys()中的键;我已经三次检查了。

所以对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 Tag 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', 'Thumbnail YResolution', 'EXIF DateTimeOriginal', 'MakerNote Tag 0x0005', 'EXIF LensMake', 'EXIF DateTimeDigitized', 'MakerNote Tag 0x0003', 'GPS GPSTimeStamp', 'EXIF ExposureTime', 'GPS Tag 0x001F', 'EXIF SubSecTimeOriginal', 'GPS GPSLatitude', 'Image Software', 'EXIF ApertureValue', 'GPS GPSDate', 'EXIF ExposureProgram', 'GPS GPSSpeed', 'EXIF ExifImageLength', 'EXIF MeteringMode', 'GPS GPSLongitudeRef', 'EXIF FocalLength', 'Image 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]

2 个答案:

答案 0 :(得分:2)

GPS GPSLatitudeGPS GPSLongitude可能不会出现在所有代码中。

而不是像tags['GPS GPSLatitude']&amp; tags['GPS GPSLongitude'],您也可以tags.get('GPS GPSLatitude')&amp; tags.get('GPS GPSLongitude')这将返回None而不是抛出错误,您可以在其中应用if-else条件来验证这些密钥不存在的位置。

答案 1 :(得分:0)

我认为@BryanOakley有正确的想法。如果密钥不在dict中,那就不存在了。 (这些字段是可选的,有些文件可能没有数据。)因此,您可以使用dict.get(key, default=None)方法,并使用默认值替换Key Error。

jpegs = [file for file in os.listdir(path) if file.endswith('.JPG')]
locns = []

for jpeg in jpegs:
    with open(jpeg,'rb') as jpf:
        exif = exifread.process_file(jpf)
        lat = exif.get('GPS GPSLatitude', 'Not available')
        lon = exif.get('GPS GPSLongitude', 'Not available')
        locns.append((lat, lon))