Saturday, 11 June 2016

pyqgis - Renaming columns in a QGIS attribute table with Python


I have some vector shape files with many columns. I need to change the name of each column in the header from the old name to a more generic "Img1", "Img2", "Img3", etc progressively, starting from column #5 and leaving the name of columns 1 to 4 unchanged.


I wrote this Python code to be used with QGIS but it doesn't work.


layer = iface.activeLayer()
nImg = 1
nCol = len(layer.pendingFields())
cont = (5,nCol)
for field in cont:
with edit (layer):

oldName = layer.fieldNameIndex(field.name())
newName = "Img" + str(nImg)
layer.renameAttribute(oldName, newName)
nImg = + 1

The error is


oldName = layer.fieldNameIndex(field.name())
AttributeError: 'int' object has no attribute 'name'

I tried also changing



with edit (layer) 

to


layer.startEditing() 

and unindenting the rows, but it doesn't work anyway.



Answer



The error is thrown by this line:


oldName = layer.fieldNameIndex(field.name())


and it is saying that field is an integer not an object with a name method. Also checking the documentation shows that:



int QgsFeature::fieldNameIndex ( const QString & fieldName )
const Utility method to get attribute index from name.


Field map must be associated using setFields() before this method can be used.


Parameters fieldName name of field to get attribute index of Returns -1 if field does not exist or field map is not associated.



So it looks up the index of a field based on its name, but you want to find the name based on its index. To do this you need to grab the qgsFields map using the fields method. So something like:


fields = layer.fields()
for field in cont:

with edit (layer):
oldName = fields.at(field).name()
newName = "Img" + str(nImg)
layer.renameAttribute(oldName, newName)
nImg = + 1

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...