pythonshapefileshapely

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


How to save shapely.geometry.polygon.Polygon object into a file (especially to a shapefile) and load it later into the Python environment when it is needed?

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

I want to save polygon object to a shapefile (or any other formatted file) and want to load it later when it is needed.


Solution

  • Late to the party. But this is how I like to do it, nice and simple with 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)
    

    OUT:

    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))
    

    cheers!