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()
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/
-
1That 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– puredata2019年12月04日 21:19:36 +00:00Commented Dec 4, 2019 at 21:19
-
3If it works, then you can accept the answer - just click on the accept icon. Thank youeurojam– eurojam2019年12月04日 21:59:29 +00:00Commented Dec 4, 2019 at 21:59
-
i didn't know about this, done, thanks a bunch again!puredata– puredata2019年12月05日 15:53:50 +00:00Commented Dec 5, 2019 at 15:53
-
1in python just use: "if not f['myfield']:" which will proof if myfield is empty...eurojam– eurojam2019年12月10日 06:20:31 +00:00Commented Dec 10, 2019 at 6:20
-
1if 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– eurojam2019年12月10日 17:18:13 +00:00Commented Dec 10, 2019 at 17:18