在RhinoPython中打开geojson文件

0 投票
1 回答
1076 浏览
提问于 2025-04-17 19:36

我希望我的问题能通过一些关于geojson的知识来解决。我遇到的问题和RhinoPython有关——这是McNeel的Rhino 5中嵌入的IronPython引擎(更多信息可以查看这里: http://python.rhino3d.com/)。我认为回答这个问题不需要成为RhinoPython的专家。

我正在尝试在RhinoPython中加载一个geojson文件。因为你不能像在普通Python中那样导入geojson模块,所以我使用了这个自定义模块GeoJson2Rhino,链接在这里: https://github.com/localcode/rhinopythonscripts/blob/master/GeoJson2Rhino.py

目前我的脚本看起来是这样的:

`import rhinoscriptsyntax as rs
 import sys
 rp_scripts = "rhinopythonscripts"
 sys.path.append(rp_scripts)
 import rhinopythonscripts

 import GeoJson2Rhino as geojson

 layer_1 = rs.GetLayer(layer='Layer 01')
 layer_color = rs.LayerColor(layer_1)

 f = open('test_3.geojson')
 gj_data = geojson.load(f,layer_1,layer_color)
 f.close()`

特别是:

 f = open('test_3.geojson')
 gj_data = geojson.load(f)

在我尝试从普通的Python 2.7中提取geojson数据时,这段代码运行得很好。然而在RhinoPython中,我收到了以下错误信息:消息:期望参数'text'是字符串,但得到了'file';这是指gj_data = geojson.load(f)这行。

我查看了上面链接的GeoJson2Rhino脚本,我认为我已经正确设置了函数的参数。根据我的观察,它似乎没有识别我的geojson文件,而是希望它是一个字符串。我可以使用其他的文件打开函数来让这个函数识别它为geojson文件吗?

1 个回答

1

根据错误信息来看,load 方法的第一个输入应该是一个 字符串,而在上面的例子中却传入了一个 文件 对象。你可以试试这样做...

f = open('test_3.geojson')
g = f.read(); # read contents of 'f' into a string
gj_data = geojson.load(g)

...或者,如果你其实并不需要这个文件对象的话...

g = open('test_3.geojson').read() # get the contents of the geojson file directly
gj_data = geojson.load(g)

想了解更多关于在 Python 中读取文件的信息,可以查看 这里

撰写回答