在ogr2ogr
中使用Python
,我正在尝试将CSV
转换为shapefile
。 CSV
中的一列名为“Polygon”,其中包含WKT
,如下所示:POLYGON((long lat, long lat, long lat, etc.))
目前,我可以使用正确的投影制作多边形shapefile
,但几何图形为空。
如何修改ogr2ogr
参数以使用每行WKT
正确创建几何图形?目前我有这样的事情:
ogr2ogr.main(["", "-a_srs", "EPSG:4326", "-f", "ESRI Shapefile", "output.shp", "input.csv", "-nlt", "POLYGON"])
答案 0 :(得分:1)
我并不习惯ogr2ogr.py,但如果你知道一些基本的python绑定ogr,它可以很容易地完成。这是一个简单的例子,可以做你想做的事情:
import ogr, osr, csv
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)
# Read the feature in your csv file:
with open('input.shp') as file_input:
reader = csv.reader(file_input) # Can be more intuitive with a DictReader (adapt to your needs)
next(reader) # Skip the header
for nb, row in enumerate(reader):
# WKT is in the second field in my test file :
poly = ogr.CreateGeometryFromWkt(row[1])
feature = ogr.Feature(dstlayer.GetLayerDefn())
feature.SetGeometry(poly)
feature.SetField("ID", nb) # A field with an unique id.
feature.SetField("Name", row[0]) # And a name (which is in the first field of my test file)
dstlayer.CreateFeature(feature)
feature.Destroy()
dstfile.Destroy()
当然需要根据您的具体情况进行调整,但这段代码可以是第一次启动并完成工作。
(如果你想在GDAL / ogr python绑定上有其他一些例子,你可以查看these recipes)