1

I have a layer with one field and I would like to rename that field with PyQGIS.

I guess it can be done using the QGIS tool "refactorfields" but I don't know how to use it in PyQGIS...

My other idea was to create a new field and next copy the values from field1 to the new field and than delete field1.

That is the code I came up with the help of the docs:

    layer.dataProvider().addAttributes([QgsField("Field_xy", QVariant.String)])

    for feature in layer.getFeatures():
        id = feature.attributes()
        feature.setAttribute('Field_xy', id[0])
        channel2.updateFeature(feature)

    layer.dataProvider().deleteAttributes([0])

unfortunately, I get the following error message:

KeyError: Field_xy

It refers to the feature.setAttribute() line. I guess it means that the field 'Field_xy' doesn't exist. But I've created the field in the line above the for loop haven't I?

2

I think you are looking for the function QgsVectorLayer.renameAttribute(index, newName) documentation is here.

And here is a minimal code example to change an attribute from old_name to new_name:

lyr = iface.activeLayer()
idx_to_change = lyr.fields().names().index(old_name)
lyr.startEditing()
lyr.renameAttribute(idx_to_change , new_name)
lyr.updateFields()
lyr.commitChanges()
| improve this answer | |
  • wow perfect, that works much better than every idea I came up with. Thanks!! – DGIS May 15 at 19:08

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.