如何将 Shapely 几何图形保存到文件中并稍后将其加载到变量中

How to save Shapely geometry into a file and load it later into a variable

如何将 shapely.geometry.polygon.Polygon 对象保存到文件中(尤其是 shapefile)并稍后在需要时将其加载到 Python 环境中?

from shapely import geometry
q = [(82,32.261),(79.304,32.474),(77.282,30.261),(81.037,28.354)]
polygon = geometry.Polygon(q)

我想将 polygon 对象保存到 shapefile(或任何其他格式化文件),并希望在需要时加载它。

派对迟到了。但这就是我喜欢的做法,用 pickle 又好又简单。

from shapely import geometry
import pickle

# Make a polygon
q = [(82,32.261),(79.304,32.474),(77.282,30.261),(81.037,28.354)]
polygon = geometry.Polygon(q)

# Check it out
print('My new polygon: \n', polygon)


# Save polygon to disc
with open('./my_polygon', "wb") as poly_file:
    pickle.dump(polygon, poly_file, pickle.HIGHEST_PROTOCOL)

# Load polygon from disc
with open('./my_polygon', "rb") as poly_file:
    loaded_polygon = pickle.load(poly_file)

# Check it out again
print('My loaded polygon: \n', loaded_polygon)

输出:

My new polygon: 
 POLYGON ((82 32.261, 79.304 32.474, 77.282 30.261, 81.03700000000001 28.354, 82 32.261))
My loaded polygon: 
 POLYGON ((82 32.261, 79.304 32.474, 77.282 30.261, 81.03700000000001 28.354, 82 32.261))

干杯!