使用python我尝试打开shapefile,添加一个功能并保存。我认为在图层中创建一个特征会导致该函数返回6(而0表示我认为没有错误)。我的代码:
# -*- coding: utf-8 -*-
from osgeo import ogr
import os
''' Add feature '''
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 for python的好文档。
答案 0 :(得分:0)
找到答案,打开文件进行阅读是个问题。 从这个资源我发现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