Key Error when key is in dictionary

主宰稳场 提交于 2019-12-02 04:24:42
Tanu

GPS GPSLatitude and GPS GPSLongitude may not be present in all tag dicts.

Instead of accessing keys as tags['GPS GPSLatitude'] & tags['GPS GPSLongitude'] , you can also access these as tags.get('GPS GPSLatitude') & tags.get('GPS GPSLongitude') This wil return None instead of throwing error, where you can apply if-else condition also to verify where these keys are not present.

I think @BryanOakley has the right idea. If the key isn't in the dict, it isn't there. (Those fields are optional, and some files might not have the data.) So you can use the dict.get(key, default=None) approach, and replace the Key Error with a default value.

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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!