4

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.

BERA
  • 72,339
  • 13
  • 72
  • 161
Linda
  • 341
  • 1
  • 12

1 Answers1

3

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

Ben W
  • 21,426
  • 3
  • 15
  • 39
  • Awesome, thank you very much for your help Ben, your answer works perfectly !!! Also I was wondering if there was an easy way to only rename fields starting by "Z10" for example ? I tried adding if layer.name().startswith('Z10') to your script but it doesn't work (even thought I don't get any error message) – Linda Aug 22 '20 at 12:58
  • 1
    @Linda, I have edited my answer. By the way, if my answer worked for you could please accept it with the check mark? – Ben W Aug 22 '20 at 13:23