如何按文件名时间顺序提取文件夹内JPG图片的EXIF元数据
解决方案
os.scandir返回的迭代器本身不保证读取顺序,你只需要先将其转换为列表,按文件名排序后再遍历即可,你的文件名是固定前缀+递增数字的格式,直接按字符串自然排序就能得到对应的时间先后顺序。
修改后的完整可运行代码如下:
#!/usr/bin/python import os, exif, folium def convert_lat(coordinates, ref): latCoords = coordinates[0] + coordinates[1] / 60 + coordinates[2] / 3600 if ref == 'W' or ref == 'S': latCoords = -latCoords return latCoords coordList=[] map = folium.Map(location=[51.50197125069916, -0.14000860301423912], zoom_start = 16) from exif import Image with os.scandir('gps/') as entries: # 核心修改:将条目转为列表并按文件名排序 sorted_entries = sorted(entries, key=lambda x: x.name) for entry in sorted_entries: img_path = 'gps/'+entry.name try: with open (img_path, 'rb') as src: img = Image(src) if img.has_exif: latCoords = convert_lat(img.gps_latitude, img.gps_latitude_ref) longCoords = convert_lat(img.gps_longitude, img.gps_longitude_ref) coord = [latCoords, longCoords] coordList.append(coord) folium.Marker(coord, popup=str(coord)).add_to(map) print(img_path) print(coord) else: print(src.name,'has no EXIF information') except Exception as e: print(img_path) print(f"error occured: {e}") # 所有坐标收集完成后一次性绘制路线,避免重复渲染浪费性能 folium.PolyLine(coordList, color="red", weight=2.5, opacity=1).add_to(map) map.save(outfile='/home/jamesdean/Desktop/Python scripts/map.html') print("Map generated successfully")
可选优化说明
- 调整了异常捕获的范围,原代码只要有一个文件出错就会终止整个遍历流程,修改后单个文件出错不会影响其他文件的处理,同时打印具体错误信息方便排查
- 把折线绘制逻辑移到了循环外,原代码每新增一个坐标点就会重复绘制整条路线,文件数量较多时会严重浪费性能,调整后所有坐标收集完成后一次性绘制即可
内容的提问来源于stack exchange,提问作者TLC
相关产品推荐
相关产品推荐

