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.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Dec 4, 2019 at 20:36

1 Answer 1

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/

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.