You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理EXIF图像对象中缺失的.gps_latitude属性问题

解决方案

你可以通过两种方式实现无GPS数据文件的自动跳过:

方法1:提前检测属性存在性

使用Python内置的hasattr()函数提前判断图片对象是否包含GPS坐标属性,仅当属性存在时执行后续计算逻辑:

from pathlib import Path
from exif import Image

files_path=Path.home()/'my path'
file_txt_path=Path.home()/'my coordinates file path'

files=list(files_path.glob("IMG_*.jpg"))

dict_files_data={}

for file in files:
   with open(file,'rb') as src:
      img=Image(src)
      # 提前判断两个GPS属性是否都存在,不存在就跳过当前文件
      if not (hasattr(img, 'gps_latitude') and hasattr(img, 'gps_longitude')):
          continue
      data=img.gps_latitude
      latitude=(data[0]+data[1]/60+data[2]/3600)*(-1)
           
      data1=img.gps_longitude
      longitude=(data1[0]+data1[1]/60+data1[2]/3600)*(-1)
          
      dict_files_data[file.name]=[latitude,longitude,img.datetime]

方法2:捕获属性不存在的异常

使用try-except块包裹坐标读取逻辑,一旦触发AttributeError就直接跳过当前文件,写法更简洁,还能兼容处理其他可能的EXIF读取异常:

from pathlib import Path
from exif import Image

files_path=Path.home()/'my path'
file_txt_path=Path.home()/'my coordinates file path'

files=list(files_path.glob("IMG_*.jpg"))

dict_files_data={}

for file in files:
   with open(file,'rb') as src:
      img=Image(src)
      try:
          data=img.gps_latitude
          latitude=(data[0]+data[1]/60+data[2]/3600)*(-1)
           
          data1=img.gps_longitude
          longitude=(data1[0]+data1[1]/60+data1[2]/3600)*(-1)
          
          dict_files_data[file.name]=[latitude,longitude,img.datetime]
      # 捕获GPS属性不存在的报错,直接跳过当前文件
      except AttributeError:
          continue

两种方案效果一致,可根据你的使用习惯选择。

内容的提问来源于stack exchange,提问作者Noe Calle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:09:03