When adding a field to a shapefile using the ogr package in python, the program crashes at the last step which is "SetFeature". This problem has been reported before, but I have not been able to resolve it based on other posts.
Here is a sample code where the dummy value '100' is added as a new field for all features in the shapefile, followed by related questions and things I tried.
Any idea what I could try ? Thank you for your time.
SDB
*EDIT : There was a conflict between this code and a module I wrote. It is hard to reproduce, so I'm settling for aworkaround : import the vexating module after the code below is used. Thank you all for your insight and time !
# Load shapefile
shapefile = ogr.Open(shapefile_path, 1)
layer = shapefile.GetLayer()
layer_defn = layer.GetLayerDefn()
new_field_defn = ogr.FieldDefn("New_field", ogr.OFTReal)
new_field_defn.SetWidth(50)
new_field_defn.SetPrecision(11)
layer.CreateField(new_field_defn)
# Walk through shapefile, setting new field for each feature
for feature in layer :
geometry = feature.GetGeometryRef()
band_value = 100
feature.SetField("New_field",np.double(band_value))
# This is the line that crashes the program
layer.SetFeature(feature)
shapefile.Destroy()
Using this solution did not work : https://gis.stackexchange.com/questions/109194/setfeature-creates-infinite-loop-when-updating-sqlite-feature-using-ogr
I believe my code follows this example : http://www.digital-geography.com/create-and-edit-shapefiles-with-python-only/#.V_0YtPnhCUk
I think I've avoided the related Gotcha http://trac.osgeo.org/gdal/wiki/PythonGotchas#PythonbindingsdonotraiseexceptionsunlessyouexplicitlycallUseExceptions