0

I am trying to select a field (column) in an attribute table for a shapefile based on whether the name of that field contains a string. Then, I need to either change the name of that selected field or create a new field and populate it with the contents of the selected field. I want to use the Python console because I need to repeat this procedure for 125 shapefiles. However, I am inexperienced with this.

For example, in the following two attribute tables, they both have a field that contains 'P.V.Q./G.P.Q.' but with different names attached. I would like to change the names of all the fields in all my shapefiles that contain 'P.V.Q./G.P.Q.' to read only 'P.V.Q./G.P.Q.'

Attribute Table 1

Attribute Table 2

My pseudo-code is:

For every shapefile in Group:
  if(shapefie_Field contains 'P.V.Q./G.P.Q.'):
    change field_name to 'P.V.Q./G.P.Q.'
  elif(shapefile_Field contains 'Q.S'):
    change field_name to 'Q.S'
  elif (etc.)

The reason is that I need to join 125 shapefiles together and the attribute fields need to match up.

1 Answer 1

1

You can try the script below. Paste the script into a new editor in the Python console and click run. With this script, you can have all of your 125 shapefiles together in a folder and just change the file path in the src_folder variable to point to that folder (see comments in script). This means you don't need to have all 125 files loaded as layers in a qgis project.

Disclaimer: running this script will permanently rename fields in your shapefiles so make backup copies of your data first if you need to.

import os

# Change the file path below to point to a directory which
# contains all of your 125 shapefiles. Back up this folder first
# in case permanently renaming fields in these files could cause a problem
src_folder = 'C:\\Path\\To\\Directory\\Containing\\Shapefiles'

def renameFields(layer):
    search_strings = ['P.V.Q./G.P.Q.', 'Q.S.']
    for fld in layer.fields():
        for s in search_strings:
            if s in fld.name():
                idx = layer.fields().lookupField(fld.name())
                with edit(layer):
                    layer.renameAttribute(idx, s)
    print('{} done'.format(layer.name()))
            

for file in os.scandir(src_folder):
    if file.name.endswith('.shp'):
        vlayer = QgsVectorLayer(file.path, file.name, 'ogr')
        renameFields(vlayer)
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.