Skip to main content
3 of 3
Commonmark migration

PyQGIS changeAttributeValue not saving modified records

I've been trying to save some changes to the a dataset using PyQGIS but I can't see any changes even after closing/reloading the layer attribute table.

I have tried a few different options but none of them work.

import re
layer = iface.activeLayer()
selection = layer.getFeatures() #all features
#selection = layer.selectedFeatures() #only selected features
layer_provider=layer.dataProvider()
layer.startEditing()
for f in selection:
   text=f['RoadMntnc'] #get the unique road id to process.
   print (text)
   stext=re.split('_+', text) #split the road id into it's components.
   print(stext)
   rtype=stext[-1:] # the type of road
   newtext=' '.join(stext[:-1]) # the road name without the road type
   print (newtext)
   attr_value={2:newtext} # the column to replace and the value to use
   #layer_provider.changeAttributeValues({1:attr_value}) #attempts to write the value
   #layer.changeAttributeValue(f.id(), RoadName, 30)
   layer.changeAttributeValue(f.id(), 2, newtext)
layer.commitChanges()
layer.updateFields()

Dataset looks like enter image description here

I want to eventually autofill the RoadName, RoadType and other fields from just the unique RoadMntnc name so that there's less work/less data entry issues when adding roads to the dataset.

GeorgeC
  • 8.3k
  • 7
  • 56
  • 143