Using python I'm trying to open a shapefile, append a feature and save it. I think it goed wrong in the creation of a feature in a layer cause that function returns 6 (and 0 means no errors I think). My code:
# -*- 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
I've copied the properties from another feature in the layer and only changed the coordinates and name.
Help would be much appreciated as I have a hard time finding good documentation for GDAL/OGR for python.
Found the answer it was a problem with opening the file for reading. From this resource I found that 0 stands for reading, 1 for writing: 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