Skip to main content
 首页 » 编程设计

python之将包含 WKT 列的 CSV 转换为 Shapefile

2025年05月04日11yxwkf

在 Python 中使用 ogr2ogr,我试图将 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"]) 

请您参考如下方法:

我不太习惯 ogr2ogr.py,但如果你了解 ogr 的 python 绑定(bind)的一些基础知识,它可以很容易地完成。这是一个简单的示例,它可以执行您想要执行的操作。

import ogr, osr, csv 
 
spatialref = osr.SpatialReference()  # Set the spatial ref. 
spatialref.SetWellKnownGeogCS('WGS84')  # WGS84 aka ESPG:4326 
driver = ogr.GetDriverByName("ESRI Shapefile") # Shapefile driver 
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 features in your csv file: 
with open('/path/to/file.csv') 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]) # The name (expected to be in the first column here) 
        dstlayer.CreateFeature(feature) 
    feature.Destroy() 
    dstfile.Destroy() 

此代码假定您的 CSV 有两列,第一列包含要使用的名称,第二列包含所要求的 WKT 中的几何图形,例如以下形式的内容:

"Name","Polygons" 
"Name1","POLYGON((1 1,5 1,5 5,1 5,1 1))" 
"Name2","POLYGON((6 3,9 2,9 4,6 3))" 

当然,它需要根据您的具体情况进行调整,但这段代码可以作为第一个开始,并且可以完成工作。
(如果你想要一些关于 GDAL/ogr python 绑定(bind)的其他例子,你可以看看 these recipes )