【发布时间】:2018-04-12 08:53:45
【问题描述】:
我正在尝试使用 python 打开一个 shapefile,添加一个特征并保存它。我认为在图层中创建功能时出错了,因为该函数返回 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
我从图层中的另一个要素复制了属性,只更改了坐标和名称。
非常感谢您的帮助,因为我很难为 Python 的 GDAL/OGR 找到好的文档。
【问题讨论】: