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?

6
  • 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, 2017 at 10:13
  • @Joseph what about versions before 2.16. I need it in 2.6.1 without Table Manager plugin.
    – drama
    Aug 2, 2017 at 8: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 2, 2017 at 9:58
  • @Joseph can you give an example
    – drama
    Aug 3, 2017 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 3, 2017 at 12:10

1 Answer 1

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()

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.