I'm trying to write a script that will update a field with 2 values (Wrong/Ok) when specific conditions are met. This is what I've come up so far, but I can't get it to work..
from qgis.core import *
from qgis.gui import *
layers = QgsMapLayerRegistry.instance().mapLayersByName('Mukono_Polygon')
layer = layers[0]
it = layer.getFeatures()
idx = layer.fieldNameIndex('PlotArea')
idy = layer.fieldNameIndex('Pr')
idz = layer.fieldNameIndex('CTRL')
layer.startEditing()
for feat in it:
if feat.attributes()[idx] <> '888.8888' and feat.attributes()[idx] <> '999.9999' and feat.attributes()[idy] > '120':
layer.changeAttributeValue(feat.attributes()[idz], 'Wrong')
elif feat.attributes()[idx] <> '888.8888' and feat.attributes()[idx] <> '999.9999' and feat.attributes()[idy] > '80':
layer.changeAttributeValue(feat.attributes()[idz], 'Ok')
else:
print 'Cant find specific entries'
layer.commitChanges()
Traceback (most recent call last):
File "", line 23, in
IOError: [Errno 9] Bad file descriptor
If remove change the line 23 to print '', the script doesnt do anything.
I chose to get the fields by name instead of their number index because it's different from shapefile to shapefile.
features id
,field
and thenew value
. Try usinglayer.changeAttributeValue(feat.id(), idz, 'Wrong')
idx
andidy
? If they are non-string, remove the string quotes around your values in yourif
statements. E.g.if feat.attributes()[idx] <> 888.8888 and feat.attributes()[idx] <> 999.9999 and feat.attributes()[idy] > 120:
feat
objects are dictionnary like, so you can change allfeat.attributes()[id]
tofeat['field_name']
.changeAttributeValue
must the id of the feature. so you need something likelayer.changeAttributeValue(feat.id(), layer.fieldNameIndex('field_name'), new_value)