将特征附加到现有的 shapefile

Append feature to an existing shapefile

使用 python 我正在尝试打开一个 shapefile,附加一个特征并保存它。我认为在图层中创建功能时出错导致该功能 returns 6(我认为 0 表示没有错误)。我的代码:

# -*- coding: utf-8 -*-
from osgeo import ogr
import os

''' Add feature '''
src = r"myShapefile.shp"
driver = ogr.GetDriverByName('ESRI Shapefile')
data_source = driver.Open(src, 0)
in_layer = data_source.GetLayer()

# create the feature
feature = ogr.Feature(in_layer.GetLayerDefn())
feature_properties = {'INDEX_NO': 39470.0,
                  'REGION_NO': 39330.0,
                  'NAME': 'VOLTRI',
                  'COUNTRY': 'IT',
                  'LATITUDE': 44.421,
                  'LONGITUDE': 8.784,
                  etc.}

for k, v in feature_properties.items():
    # Set the attributes using the values from the dictionary
    feature.SetField(k, v)

# create the WKT for the feature using Python string formatting
wkt = "POINT(%f %f)" %  (float(feature_properties['LONGITUDE']) , float(feature_properties['LATITUDE']))

# Create the point from the Well Known Txt
point = ogr.CreateGeometryFromWkt(wkt)

# Set the feature geometry using the point
feature.SetGeometry(point)
feature.SetFID(in_layer.GetFeatureCount())

# Create the feature in the layer (shapefile)
print(in_layer.CreateFeature(feature)) # prints 6, I would expect 0

# Dereference the feature
feature.Destroy()

# Save and close the data source
data_source = None

我复制了图层中另一个要素的属性,只更改了坐标和名称。

非常感谢您的帮助,因为我很难找到 GDAL/OGR 和 python 的良好文档。

找到了打开文件进行阅读时出现问题的答案。 从这个资源中我发现 0 代表阅读,1 代表写作:https://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html

data_source = driver.Open(src, 0) # for reading
data_source = driver.Open(src, 1) # for writing