1

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.

2

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

lyr = iface.activeLayer()
fts = lyr.getFeatures()
lyr.startEditing()
for f in fts:
    f['myfield']='mystring'
    lyr.updateFeature(f)
lyr.commitChanges() #ends the editing session and commit all changes

for some good examples see:
https://anitagraser.com/pyqgis-101-introduction-to-qgis-python-programming-for-non-programmers/pyqgis101-creating-editing-a-new-vector-layer/
or
https://docs.qgis.org/3.4/en/docs/pyqgis_developer_cookbook/

  • 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! – reGIS Dec 4 '19 at 21:19
  • 3
    If it works, then you can accept the answer - just click on the accept icon. Thank you – eurojam Dec 4 '19 at 21:59
  • i didn't know about this, done, thanks a bunch again! – reGIS Dec 5 '19 at 15:53
  • 1
    in python just use: "if not f['myfield']:" which will proof if myfield is empty... – eurojam Dec 10 '19 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 '19 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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