Folium加载world.json触发FileNotFoundError但文件存在问题求助
问题:Folium加载GeoJSON文件失败的排查与解决
问题详情
用户编写了以下代码尝试用Folium加载GeoJSON多边形:
import pandas import folium map1 = folium.Map(zoom_start = 6, tiles = "Stamen Terrain") vol = pandas.read_csv("Volcanoes.txt") lat = list(vol["LAT"]) lon = list(vol["LON"]) name = list(vol["NAME"]) loc = list(vol["LOCATION"]) elev = list(vol["ELEV"]) html = """ Hello, My name is %s, i live in %s with an elevation of %s meters high """ def color_code(elevation): if elevation < 1000: return "green" elif 1000 <= elevation <= 3000: return "orange" else: return "red" fg = folium.FeatureGroup(name="My Map") for lt, ln, n, l, e in zip(lat, lon, name, loc, elev): iframe = folium.IFrame(html=html % (n, l, str(e)), width=200, height=110) fg.add_child(folium.CircleMarker(location=(lt, ln), radius=6, popup=folium.Popup(iframe, parse_html=True), fill_color = color_code(e), color = None, fill_opacity = 1)) fg.add_child(folium.GeoJson(data=open('world.json','r').read())) map1.add_child(fg) map1.save("Map1.html")
运行时触发FileNotFoundError,异常栈如下:
FileNotFoundError Traceback (most recent call last) Cell In[4], line 24 21 iframe = folium.IFrame(html=html % (n, l, str(e)), width=200, height=110) 22 fg.add_child(folium.CircleMarker(location=(lt, ln), radius=6, popup=folium.Popup(iframe, parse_html=True), fill_color = color_code(e), color = None, fill_opacity = 1)) ---> 24 fg.add_child(folium.GeoJson(data=data_json.read())) 25 map1.add_child(fg) 26 map1.save("Map1.html") File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\folium\features.py:643, in GeoJson.__init__(self, data, style_function, highlight_function, name, overlay, control, show, smooth_factor, tooltip, embed, popup, zoom_on_click, marker) 638 raise TypeError( 639 "Only Marker, Circle, and CircleMarker are supported as GeoJson marker types." 640 ) 641 self.marker = marker --> 643 self.data = self.process_data(data) 645 if self.style or self.highlight: 646 self.convert_to_feature_collection() File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\folium\features.py:680, in GeoJson.process_data(self, data) 678 if not self.embed: 679 self.embed_link = data --> 680 with open(data) as f: 681 return json.loads(f.read()) 682 elif hasattr(data, "__geo_interface__"): FileNotFoundError: [Errno 2] No such file or directory:
移除.read()后又触发ValueError: Cannot render objects with any missing geometries,且确认world.json与代码在同一目录。
错误原因分析
FileNotFoundError原因:
Folium的GeoJson类对data参数的处理逻辑是:如果传入字符串,会先尝试将其当作文件路径去读取。当你用open('world.json').read()时,传入的是JSON文件的内容字符串,Folium误以为这是一个文件路径,自然找不到对应的文件,抛出错误。ValueError原因:
直接传入文件对象时,若文件编码与默认读取编码(如cp1252)不匹配,会导致JSON解析失败;或者world.json本身的GeoJSON结构不规范(比如缺少geometry字段、Feature格式错误),都会触发“缺失几何信息”的报错。
解决方案
方案1:直接传入文件路径(推荐)
Folium会自动处理文件的读取和解析,无需手动打开:
fg.add_child(folium.GeoJson(data='world.json'))
方案2:手动读取并解析JSON对象
手动指定编码读取文件,避免编码问题,同时解析为JSON对象后传入:
import json # 读取并解析GeoJSON文件 with open('world.json', 'r', encoding='utf-8') as f: geo_json_data = json.load(f) # 添加到FeatureGroup fg.add_child(folium.GeoJson(data=geo_json_data))
方案3:检查GeoJSON文件结构
确保world.json符合标准GeoJSON规范:
- 根节点应为
FeatureCollection,包含features数组 - 每个
Feature必须包含geometry字段(类型如Polygon、MultiPolygon)和properties字段
额外注意事项
- 确认代码运行的工作目录确实是
world.json所在的目录(可通过print(os.getcwd())查看当前工作目录) - 若文件路径包含中文或特殊字符,建议使用绝对路径
内容的提问来源于stack exchange,提问作者Rookie-kinda
相关产品推荐
相关产品推荐

