3

I am trying to write a PyQGIS script that copies information from one feature into an output feature and adds a field.

This is how I'm initializing my fields for my output layer

inlayer = processing.getObject(input_layer)
provider = inlayer.dataProvider()
fields = provider.fields()
fields.append( QgsField("NewField", QVariant.Double) )
writer = QgsVectorFileWriter(output_layer, 'UTF-8', fields, QGis.WKBPoint, inlayer.crs())

I'm then looping through the features and adding output features to my writer

outFeature = QgsFeature(fields)
outFeature.setGeometry(setting the geometry... nothing to see here)
outFeature.setAttributes(inFeature.attributes()) #copying attributes from the input layer
outFeature.setAttribute("NewValue", newValue) #this line is what is causing the error
writer.addFeature(outFeature)

When I run the script I am getting an steady stream of error messages in the log messages panel under the General tab

Attribute index 9 out of bounds [0;9]

If I check the attributes table for the output layer that I just created, I have all the fields that I'm expecting. I have all the attributes from the input layer, and I have a column for the NewValue, but I do not have any data populated in the NewValue column. The NewValue column is the 10th column, so I'm confused why my script is failing to write to that column saying index 9 is out of bounds because I would think that the NewValue column would be index 9. What am I missing or doing wrong?

2 Answers 2

1

You may try using something like this:

outFeature = QgsFeature(fields)
outFeature.setGeometry(setting the geometry... nothing to see here)
attrs = inFeature.attributes()
attrs.append(newValue)
outFeature.setAttributes(attrs)
writer.addFeature(outFeature)

instead of:

outFeature = QgsFeature(fields)
outFeature.setGeometry(setting the geometry... nothing to see here)
outFeature.setAttributes(inFeature.attributes()) #copying attributes from the input layer
outFeature.setAttribute("NewValue", newValue) #this line is what is causing the error
writer.addFeature(outFeature)

In this way, you directly add the initial attributes plus the new field.

1

I was able to fix my problem by looping through the attributes and adding them individually. It seems kind of silly to have to do this and I'm wondering if this is a bug.

attributeIndex = 0
for fAttribute in inFeature.attributes()
    outFeature.setAttribute(attributeIndex, fAttribute)
    attributeIndex += 1

Your Answer

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

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