Dictionary key does not exist - but it does
本问题已经有最佳答案,请猛点这里访问。
我用
目前,我正在尝试获取GPS纬度和经度,我可以做到:
1 2 3 4 5 6 7 8 9 10 | def main(): images = image_paths(IMAGE_FOLDER) # folder is say"Sample Photos\" info = {} for img in images: _lat, _lon ="","" tags = exifread.process_file(open(img,'rb')) for i in tags.keys(): if i =="GPS GPSLatitude": print(i,":::", tags[i]) |
这将打印我所期望的,它们的键名和值:
GPS GPSLatitude ::: [32, 52, 66443/1250] GPS GPSLatitude ::: [32, 52,
531699/10000] GPS GPSLatitude ::: [32, 52, 531699/10000] GPS
GPSLatitude ::: [32, 52, 132789/2500] GPS GPSLatitude ::: [32, 52,
265817/5000]
但是,为了跳过这个循环,快速地获取键/值对,我正在尝试(这将取代
1 | _lon = tags["GPS GPSLatitude"] |
但我得到一个错误:
KeyError: 'GPS GPSLatitude'
如何访问"GPS gpslateitude"(和"GPS gpslongitude"),而不通过
编辑:
是否可能某些标签没有密钥
也许你可以试试
1 | _lat = tags.get('GPS GPSLatitude', '') |
这样,如果存在
如果任何图像没有该标记,则需要处理该异常以防止崩溃。例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 | def main(): images = image_paths(IMAGE_FOLDER) # folder is say"Sample Photos\" info = {} for img in images: _lat, _lon ="","" tags = exifread.process_file(open(img,'rb')) try: _lon = tags["GPS GPSLongitude"] # _lat = tags["GPS GPSLatitude"] # presumably you also want this # do something with these... perhaps add to info except KeyError: pass # move on |