2

I am very new to QGIS.

I have added three new fields using batch processor to all my layers (150 or so), but named them incorrectly. All I want to do is rename them correctly but I can't seem to do this. Everything involves creating new layers with the renamed column (refractor fields) or if I deleted the columns and add them again then again it creates new layers without them and keeps the old ones. It will take forever to save all these files under a new name and a new place, so I was wondering if there is any way to delete or rename the columns in the same layers and not create new ones.

  • 1
    Why don't you simply redo the batch processing with the correct names? – Erik Sep 26 '19 at 9:27
  • Thanks for your reply, yeah I've done that but is there any way to batch delete the incorrect fields without creating whole new layers? – Sally Sep 26 '19 at 9:35
  • Toggle editing, then delete them via the attribute table - which is manually. – Erik Sep 26 '19 at 9:40
  • @Sally - You should be able to do this with a little scripting if you have experience in using Python for QGIS. – Joseph Sep 26 '19 at 9:42
  • This could be a good starting point gis.stackexchange.com/questions/250288/… – user30184 Sep 26 '19 at 9:55
3

I think a script would be beneficial for this amount of layers. If you load all your layers into QGIS, you can copy/paste the following code into the Python Console (load the console using Ctrl + Alt + P). Replace the names in the dictionary with your own:

# Dictionary to hold old names as keys; new names as values
dict_of_field_names = { 'A': 'new_A',
                        'B': 'new_B',
                        'C': 'new_C'
                        }

# Iterate through each layer
for layer in QgsProject.instance().mapLayers().values():
    # Store all field names in a list
    fields = [field.name() for field in layer.fields()]
    # Iterate through each field
    for field in layer.fields():
        # Check if old field name matches those in the dictionary
        if field.name() in dict_of_field_names:
            # If yes then edit the layer
            with edit(layer):
                # Get index of field containing the old field name
                idx = layer.fields().indexFromName(field.name())
                #  Change old field name to its corresponding new field name
                layer.renameAttribute(idx, dict_of_field_names[field.name()])

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.