Search code examples
pythonvectorgdalogr

Writing values to new field, Python GDAL OGR, not sure how to commit the changes, why are my fields still empty?


Im reading in some s-57 from 2 sources using gdal/ogr and writing it to a memory datasourse. The data is loading sucessfully and I can see layers and values etc.

encdriver = ogr.GetDriverByName("S57")

new_enc = encdriver.Open(new_enc_path)
old_enc = encdriver.Open(new_enc_path)

memdriver=ogr.GetDriverByName('MEMORY')
memsource=memdriver.CreateDataSource('memData')

tmp=memdriver.Open('memData',1)

memsource.CopyLayer(new_enc.GetLayerByName('lights'), 'new_lights',['OVERWRITE=YES'])
memsource.CopyLayer(old_enc.GetLayerByName('lights'), 'old_lights',['OVERWRITE=YES'])

new_lights = memsource.GetLayerByName('new_lights')
old_lights = memsource.GetLayerByName('old_lights')

I am then defining a new field (boolean) and adding it to the layer then setting it to true or false in each layer.

new_field = ogr.FieldDefn('NEW', ogr.OFSTBoolean)
new_lights.CreateField(new_field)
old_lights.CreateField(new_field)

layerDefinition = new_lights.GetLayerDefn()
print(layerDefinition.GetFieldCount())

new_lights.ResetReading()
old_lights.ResetReading()
print('NEW')
for feat in new_lights:
    feat.SetField('NEW', True)
    new_lights.CommitTransaction()
    print(feat.GetField('NEW'))


print('OLD')   
for feat in old_lights:
    feat.SetField('NEW', False)
    old_lights.CommitTransaction()
    print(feat.GetField('NEW'))

In both the loops above the field is printed with the new value [0] or [1]

print('OLD2')
old_lights.ResetReading()
for feat in old_lights:
    print(feat.GetField('NEW'))

but when I try and read these layers after the above loop, the new field is 'None', has no values, I tried adding datasource.CommitTransaction() but it doesnt seem to have helped. Could someone help explain what Im missing here, Im not sure why the values are not being written to the field but I can see the field does now exist.


Solution

  • I should of continued reading, found this, seems I was a bit early posting a question.

    This function is the same as the C++ method OGRFeature::SetField().

    This method has only an effect on the in-memory feature object. If this object comes from a layer and the modifications must be serialized back to the datasource, OGR_L_SetFeature() must be used afterwards. Or if this is a new feature, OGR_L_CreateFeature() must be used afterwards.