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?
-
1A 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 :)– JosephMay 22, 2017 at 10:13
-
@Joseph what about versions before 2.16. I need it in 2.6.1 without Table Manager plugin.– dramaAug 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.– JosephAug 2, 2017 at 9:58
-
@Joseph can you give an example– dramaAug 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 :)– JosephAug 3, 2017 at 12:10
1 Answer
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()