生成folium地图时触发FileNotFoundError的解决方法
修复folium生成地图的FileNotFoundError错误
这个错误的核心原因是static/maps目录不存在——Python的open()函数只能创建文件,无法自动创建上级目录,因此写入文件前必须先确保目标目录存在。以下是具体修复步骤:
1. 自动创建缺失的目录
在写入地图HTML文件前,添加目录创建逻辑,使用os模块确保static/maps目录存在:
import os # 你的folium地图生成代码保持不变 map = folium.Map(location=[points[0]["latitude"], points[0]["longitude"]], zoom_start=12) folium.Marker([points[0]["latitude"], points[0]["longitude"]], popup='<i>Start</i>', color='green', fill_color='green').add_to(map) folium.Marker([points[-1]["latitude"], points[-1]["longitude"]], popup='<i>End</i>', color='red', fill_color='red').add_to(map) folium.PolyLine(locations=[[p["latitude"], p["longitude"]] for p in points], color="blue", weight=2.5, opacity=1).add_to(map) map_html = map.get_root().render() map_path = 'static/maps/route_map.html' # 提取目录路径并创建(exist_ok=True避免目录已存在时报错) os.makedirs(os.path.dirname(map_path), exist_ok=True) # 写入文件 with open(map_path, 'w') as file: file.write(map_html)
2. 确保路径的准确性
如果你的Flask应用结构复杂,建议使用应用根目录拼接绝对路径,避免相对路径出错:
from flask import current_app import os # 基于Flask应用根目录生成绝对路径 map_path = os.path.join(current_app.root_path, 'static', 'maps', 'route_map.html') os.makedirs(os.path.dirname(map_path), exist_ok=True) with open(map_path, 'w') as file: file.write(map_html)
3. 模板中正确引用地图路径
前端无法直接访问服务器本地路径,在home.html中需用Flask的url_for生成可访问的静态资源URL:
<!-- 示例:用iframe嵌入地图 --> <iframe src="{{ url_for('static', filename='maps/route_map.html') }}" width="100%" height="600"></iframe>
内容的提问来源于stack exchange,提问作者zuokox
相关产品推荐
相关产品推荐

