4

Is there a straight method to export shapefile geometry (polygon) to WKT using pyshp module for python?

I was looking for something similar to OGR's .ExportToWkt() method, but it seems like there's nothing similar implemented in pyshp

4

Pyshp does not have a WKT method but it does support the geo_interface protocol at the shape level. That protocol returns each shape as geojson. You can then use the lightweight, pure-python pygeoif module to convert to WKT.

The pygeoif module is available on the Python Package Index and Github:

The following example converts a point shapefile to MultiPoint WKT. Note the shapefile is just a point shapefile, not MultiPoint, but it makes it easier to see the WKT output:

import shapefile
import pygeoif

r = shapefile.Reader("my_point_shapefile")

g=[]

for s in r.shapes():
    g.append(pygeoif.geometry.as_shape(s)) 

m = pygeoif.MultiPoint(g)

print m.wkt

# 'MULTIPOINT(38.8897 -77.0089, 32.30642 122.61458)'

The geometry variable "g" contains the individual points as WKT. You could also use pyshp's shapeRecords() method combined with pygeoif's feature() method to collect the attributes in addition to the geometry and convert to a FeatureCollection. The examples on github for both libraries demonstrate these methods individually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.