TypeError:应为str、bytes或os.PathLike对象,而不是GeojsonFile

2024-10-03 21:35:07 发布

您现在位置:Python中文网/ 问答频道 /正文

数据文件=打开(文件名为“r”); TypeError:应为str、bytes或os.PathLike对象,而不是GeojsonFile

有人能帮我解释一下为什么会这样吗?我想读取geojson格式的空间数据

我想将geojson数据存储到数据库中。我已经连接了数据库,它是MongoDB数据库。我使用gridfs来克服这个限制,但是首先我需要读取数据并存储到数据库中

非常感谢

    #read in the spatial data
filename = "/dami_data/data1/countries.geojson"
geojfile = pygeoj.load(filename)
for feature in geojfile:
    print(feature.geometry.type)
    print(feature.geometry.coordinates)
datafile = open(filename, "r")
thedata = datafile.read()

#create a gridFS object 
filesystem = gridfs.GridFS(db, collection='data')

#write data to GridFS
myfile = filesystem.put(thedata, filename = "countries")
print ("Store to database :)")

#retrieve what was just stored/document
filesystem.get(myfile).read()

Tags: in数据库readdatageojsonfilenamecountriesfeature
1条回答
网友
1楼 · 发布于 2024-10-03 21:35:07

在代码中,filename引用GeojsonFile对象而不是文件名

如果要读取的原始文件与pygeoj读取的文件相同,则应执行以下操作:

filename = "/dami_data/test_data/roads.geojson"
geojfile = pygeoj.load(filename)
for feature in geojfile:
    print(feature.geometry.type)
    print(feature.geometry.coordinates)
datafile = open(filename, "r")
thedata = datafile.read()
datafile.close()

尽管您可以这样做,但是您应该考虑使用^ {CD2>},而不是再次读取文件。它已经保存了您从该文件中需要的信息(正如@Karl Knechtel在注释中指出的)

如果不是,则意味着您要读取不同的文件,您应该传递文件名:

filename = "/dami_data/test_data/roads.geojson"
geojfile = pygeoj.load(filename)
for feature in geojfile:
    print(feature.geometry.type)
    print(feature.geometry.coordinates)
datafile = open("my_other_file_name", "r")
thedata = datafile.read()
datafile.close()

最后一种情况是,如果要获取该GeojsonFile的原始数据,请执行以下操作:

filename = "/dami_data/test_data/roads.geojson"
geojfile = pygeoj.load(filename)
for feature in geojfile:
    print(feature.geometry.type)
    print(feature.geometry.coordinates)
thedata = str(geojfile)

相关问题 更多 >