TransWikia.com

PyQGIS: looping over shapefile's fields to rename them using substring

Geographic Information Systems Asked on March 2, 2021

I’m trying to rename multiple field names (about 150) of a shapefile in QGIS. Their names are different but they all end by _xf20 and I would like to remove this part for each of them.

I’ve looked up to other topics that could help and I’ve found this one: Rename fields of shapefile using PyQGIS 3 with the code:


layer = iface.activeLayer()

# Open editing session
layer.startEditing()

# Rename field
for field in layer.fields():
    if field.name() == 'oldName':
        idx = layer.fields().indexFromName(field.name())
        layer.renameAttribute(idx, 'newName')

# Close editing session and save changes
layer.commitChanges()

and this one: Delete all fields with the string "RAWI" using QGIS Python

But even if it is a start, I’m a beginner with Python and I don’t find a way to adapt them for my case.

I would rather not edit every single field manually.

One Answer

The following should work by slicing your old field names to return everything before the last 5 characters'_xf20' which you want to remove.

While I have tested this in QGIS 3.14.15 and it worked fine for me, please make a backup copy of your shapefile first just in case something goes wrong.

layer = iface.activeLayer()

layer.startEditing()

for field in layer.fields():
    if field.name().startswith('Z10'):
        idx = layer.fields().lookupField(field.name())
        new_name = field.name()[:-5]
        layer.renameAttribute(idx, new_name)

layer.commitChanges()

Correct answer by Ben W on March 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP