To import the WKT string from CSV into shapfile, you can use ogr and osr module to transform.
I write the python script to transform the field of CSV(WKT, Name) into shapfile:
import ogr, osr, cs
def csv2shp(fileInput):
spatialref = osr.SpatialReference() # Set the spatial ref.
spatialref.SetWellKnownGeogCS('WGS84') # WGS84 aka ESPG:4326
driver = ogr.GetDriverByName("ESRI Shapefile")
dstfile = driver.CreateDataSource('output.shp') # Your output file
# Please note that it will fail if a file with the same name already exists
dstlayer = dstfile.CreateLayer("layer", spatialref, geom_type=ogr.wkbPolygon)
# Add the other attribute fields needed with the following schema :
fielddef = ogr.FieldDefn("ID", ogr.OFTInteger)
fielddef.SetWidth(10)
dstlayer.CreateField(fielddef)
fielddef = ogr.FieldDefn("Name", ogr.OFTString)
fielddef.SetWidth(80)
dstlayer.CreateField(fielddef)
fielddef = ogr.FieldDefn("WKT", ogr.OFTString)
fielddef.SetWidth(80)
dstlayer.CreateField(fielddef)
# Read the feature in your csv file:
with open(fileInput) as file_input:
reader = csv.reader(file_input)
next(reader) # Skip the header
for nb, row in enumerate(reader):
# WKT is in the first field in my test file :
poly = ogr.CreateGeometryFromWkt(row[0])
feature = ogr.Feature(dstlayer.GetLayerDefn())
feature.SetGeometry(poly)
feature.SetField("ID", nb) # A field with an unique id.
feature.SetField("WKT", row[0])
feature.SetField("Name", row[1])
dstlayer.CreateFeature(feature)
feature.Destroy()
dstfile.Destroy()
return dstfile
if __name__ == "__main__":
csv2shp(r"C:\Users\USER\Desktop\TEST.csv")
You can also use this method in QGIS plugin.