I'm trying to automate a simple repetitive task on QGIS. I have some shapefiles with varying number of features in a layer and about 10 different attributes for each feature. I need to add the same string value ("negative") to one of these attributes, over and over again. Copy, paste works but since I want to sharpen my Python scripting skills I'd like to achieve this by creating a simple Python script.

I'm able to print values of attributes using something like this;

layer = iface.activeLayer()

for feature in layer.getFeatures():

    print("{acreage} acres in {name}".format(name=feature['fieldname'],acreage=feature['acreage']))

But I'm stuck at this point. How would I write "negative" to the attribute "acreage"? I tried set.Feature() but it just didn't work.

1 Answer 1


You are not far away, just some lines of code:

lyr = iface.activeLayer()
fts = lyr.getFeatures()
for f in fts:
lyr.commitChanges() #ends the editing session and commit all changes

for some good examples see:

  • 1
    That works! Thank you so much! I wish I asked earlier, spent all day trying to get this working. I already got to the point using and combining examples on anitagraser.com . Thank you so much again!
    – puredata
    Dec 4, 2019 at 21:19
  • 3
    If it works, then you can accept the answer - just click on the accept icon. Thank you
    – eurojam
    Dec 4, 2019 at 21:59
  • i didn't know about this, done, thanks a bunch again!
    – puredata
    Dec 5, 2019 at 15:53
  • 1
    in python just use: "if not f['myfield']:" which will proof if myfield is empty...
    – eurojam
    Dec 10, 2019 at 6:20
  • 1
    if not f['POSITIVE']: means that there is a fieldname 'POSITIVE'. The error says, that there is no field called 'POSITIVE'. I suppose the code should be like this: if not f['MARK']: ... which means the field MARK is empty...
    – eurojam
    Dec 10, 2019 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.