TransWikia.com

Rename fields of shapefile using PyQGIS 3

Geographic Information Systems Asked by joseph_k on May 27, 2021

I am using the following script through QGIS 3.4 “Python Console” to rename field names of shapefiles. The input will be a CSV file with 1st row – shapefile name, 2nd row – old field name, 3rd row – new field name. Also, I have used this code in QGIS 2.18 (got the code from Renaming field in attribute table via PyQGIS?) and slightly modified w.r.t Python 3 specifications.

from PyQt5.QtCore import (QCoreApplication, 
                      QVariant)
from qgis.core import (QgsProcessing, 
                       QgsVectorLayer,     
                       QgsProject,     
                       QgsApplication,
                       QgsFeature,
                       QgsFeatureSink,
                       QgsFields,
                       QgsField,
                       QgsGeometry,
                       QgsPoint,
                       QgsPointXY,
                       QgsRectangle,
                       QgsWkbTypes,
                       QgsSpatialIndex,
                       QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterField,
                       QgsProcessingParameterString,
                       QgsProcessingParameterBoolean,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterFile,
                       QgsProcessingParameterFeatureSink)

from osgeo import gdal,osr,ogr
from os import path
import csv, os

csvpath = r"D:Testvedrename_fld.csv"
with open(csvpath, "r") as csvfile:
    reader = csv.reader(csvfile)    

    for row in reader:
        one = row[0]
        layer = QgsVectorLayer(one,'','ogr')
        two = row[1]
        fromfld = QgsField(two).name()
        three = row[2]
        tofld = QgsField(three).name()
        for field in layer.fields():
            if field.name() == fromfld:
                try:
                    with edit(layer):
                        idx = layer.fields().indexFromName(field.name())
                        layer.renameAttribute(idx, tofld)
                        print ("Changed Successfully")
                except Exception as ex:
                    print(ex)

Code runs without any issues and name is getting changed properly.

But if I run the code through processing toolbox as python script, I am getting “NameError”. Below is the code I’ve used and the error it’s throwing

def initAlgorithm(self, config=None):

    # We add the input File Parameter.
    self.addParameter(QgsProcessingParameterFile(self.INPUT,self.tr('csv File'),0,'csv'))

def processAlgorithm(self, parameters, context, feedback):
    inputFile = self.parameterAsFile(parameters, self.INPUT, context)


    with open(inputFile, "r") as csvfile:
        reader = csv.reader(csvfile)

        for row in reader:
            one = str(row[0])
            layer = QgsVectorLayer(one,"","ogr")
            two = str(row[1])
            fromfld = QgsField(two).name()
            three = str(row[2])
            tofld = QgsField(three).name()

            for field in layer.fields():
                if field.name() == fromfld:
                    with edit(layer):
                        idx = layer.fields().indexFromName(field.name())
                        layer.renameAttribute(idx, tofld)
                        print ("Changed Successfully")

Traceback (most recent call last):
File "<string>", line 84, in processAlgorithm
NameError: name 'edit' is not defined

Execution failed after 0.15 seconds

2 Answers

I got the same error name 'edit' is not defined so I found another way. I made this example with an activeLayer() :

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

Answered by GeoGyro on May 27, 2021

You need to import the qgis.core.edit class.

from qgis.core import edit

Answered by bonzinor on May 27, 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