[GIS] Converting a CSV with a WKT column to a Shapefile

ogr2ogrpythonwell-known-text

Using ogr2ogr in Python, I am trying to convert a CSV to a shapefile. One column in the CSV, named "Polygon", contains WKT like this: POLYGON((long lat, long lat, long lat, etc.)) Currently, I can make a polygon shapefile with the correct projection, but the geometry is empty. How can I modify my ogr2ogr arguments to correctly create the geometry using the WKT in each row? Currently I have something like this:

ogr2ogr.main(["", "-a_srs", "EPSG:4326", "-f", "ESRI Shapefile", "output.shp", "input.csv", "-nlt", "POLYGON"])

Best Answer

I don't know if it will help you but i tested with ogr2ogr command line tool and this command do the job (assuming 'Polygon' is the field containing the geometry in WKT) :

ogr2ogr -f "ESRI Shapefile" output.shp -dialect sqlite -sql "SELECT *, GeomFromText(Polygon) FROM input" input.csv -a_srs "WGS84"

Maybe you could adapt that to the ogr2ogr python tool ?

I also posted an answer on Stack Overflow, using ogr python bindings (it basically do the same, but its more than 1 line of code..!)

EDIT : I tested with the ogr2ogr python tool and i it seems that the -dialect parameter is not implemented.
However, if you cant find better option, it works if you call ogr2ogr (the command line tool) with subprocess in python :

In [24]: import subprocess

In [25]: subprocess.call(["ogr2ogr", "-a_srs", "WGS84", "-f", "ESRI Shapefile",
                          "output.shp", "input.csv", "-dialect", "sqlite",
                          "-sql", "SELECT *, GeomFromText(Polygon) FROM input"])
Out[25]: 0

As you see it will return the returncode of the process (here, 0 if it success or 1 if it fails).
(tested with GDAL 1.11.2 / python 3.4)