Creating Polygon Shapefile from list of X,Y coordinates using Python?
From the pyshp documentation page:
>>> # Create a polygon shapefile
>>> w = shapefile.Writer(shapefile.POLYGON)
>>> w.poly(parts=[[[1,5],[5,5],[5,1],[3,3],[1,1]]])
>>> w.field('FIRST_FLD','C','40')
>>> w.field('SECOND_FLD','C','40')
>>> w.record('First','Polygon')
>>> w.save('shapefiles/test/polygon')
Just substitute your list for the parts=
argument to Writer.poly
, and set whatever fields you would like to associate with your shapefile.
This expands on the answer posted by BradHards:
The error message sounds like pyshp is expecting float
s where it is not getting them. If your coordinate list is a set of int
s, try casting them to float
s:
shape = [[1,5], [5,5], [5,1], [3,3], [1,1]]
shape = [[float(coord) for coord in pair] for pair in shape]
One easy (one time) solution is to use the QuickWKT Plugin.
Transform your list into a EWKT string by adding a the header with the SRID and the type of geometry. Add a comma in the end of each XY pair.
SRID=4326;POLYGON
((
30 10,
10 20,
20 40,
40 40,
30 10
))
Copy + paste the all thing to QuickWKT Plugin's dialog, and press OK.
Your polygon will be created in a memory layer in QGIS. After that, you can do whatever you want with it, including Save as... (Shapefile).