How can I rename a field in PyQGIS?

I tried:

for field in layer.pendingFields():
    if field.name() == 'old':
        oldname = field.name()
        newname = field.name()
        print(u'Old name: {}, New name: {}'.format(oldname,newname))

This code print 'Old name: old, New name: new', but in attribute table is field name still 'old'.

  • What does it do? Do you get errors or does it do something else? Please edit your question to include this info – Midavalo May 20 '17 at 21:50

I think the QgsField::setName() method is only used for creating new fields. If you want to rename your field, you can use QgsVectorLayer::renameAttribute() method in Qgis 2.16 and above:

layer = iface.activeLayer()
for field in layer.pendingFields():
    if field.name() == 'old':
        with edit(layer):
            idx = layer.fieldNameIndex(field.name())
            layer.renameAttribute(idx, 'new')
  • I used this code to update the field names 3 times sequentially, and it worked flawlessly the first two times. The third attempt at renaming the field yielded a 'layer not editable' error, which is strange considering the layer was edited twice immediately before then. Do you have any insight for why this is occurring? – GIS_Canuck Jul 11 '17 at 18:10
  • If I change the 'with edit(layer)' line to 'layer.startEditing()', and then unindent the rest of the code, there are no problems updating the final field. Not sure why this is happening, but thankfully everything is working as anticipated now. – GIS_Canuck Jul 11 '17 at 19:05
  • @GIS_Canuck - That is strange, not sure why with edit(layer) is a problem. Sounds like a bug to me. You could consider posting a bug report with a reproducible method but glad you found another method :) – Joseph Jul 12 '17 at 8:58
  • 2
    in QGis 3, QgsVectorLayer.fieldNameIndex is replaced by fields().lookupField() or fields().indexFromName() (see here). In this example, replace idx = layer.fieldNameIndex(field.name()) by idx = layer.pendingFields().indexFromName(field.name()) – Lennert Feb 27 '18 at 11:05
  • It doesn't work for 2.84 – Chetan Vashisth Nov 12 '19 at 12:45

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.