5

By using the table manager we can rename the field names but i want to rename of fields using python. How can i do that?

user99
  • 979
  • 2
  • 15
  • 36
  • 1
    A recent but very similar question was asked (I just noticed yours) where you can use the QgsVectorLayer::renameAttribute() method. Note that this method was introduced in QGIS 2.16 :) – Joseph May 22 '17 at 10:13
  • @Joseph what about versions before 2.16. I need it in 2.6.1 without Table Manager plugin. – drama Aug 02 '17 at 08:58
  • @drama - I don't think there's an API for this method for QGIS 2.6. You may need to use the same method Table Manager uses which is to copy the .dbx file whilst changing the name of the field and replacing the existing one. – Joseph Aug 02 '17 at 09:58
  • @Joseph can you give an example – drama Aug 03 '17 at 11:53
  • 1
    @drama - Unfortunately, I cannot at this time. The plugin is also quite involved as it makes a copy of the shapefile and replaces the old .dbf file with a new one. Alternatively, it is possible to read/write directly to the .dbf file as described in this post: DBF reader and writer (Python recipe). Be advised, directly modifying the .dbf file can be very risky so make sure you keep backups of your data :) – Joseph Aug 03 '17 at 12:10
  • I have a few colleagues reporting data integrity problems with this "Table Manager" plugin (although i never saw it myself). I would recommend refactor field in the processing tools rather than table manager, i possible (but that doesn't answer at all the question) :) – gisnside Sep 08 '17 at 18:55

1 Answers1

3

You can use an OGR SQL ALTER TABLE statement to RENAME the column:

from osgeo import gdal

layer = iface.activeLayer()
oldFieldName = 'oldFieldName'
newFieldName = 'newFieldName'
ds = gdal.OpenEx(layer.source(), gdal.OF_VECTOR | gdal.OF_UPDATE)
ds.ExecuteSQL('ALTER TABLE {} RENAME COLUMN {} TO {}'.format(layer.name(), oldFieldName, newFieldName))
layer.reload()
Antonio Falciano
  • 14,333
  • 2
  • 36
  • 66