2

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:\Test\ved\rename_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
  • 1
    Are you importing all the same modules in your second script as you are in your first? I would guess that perhaps running the code in the console is performing some imports in the background which is not being done when executing from the toolbox. Can you look up where edit() is being defined?
    – wfgeo
    Commented Mar 30, 2019 at 9:20
  • Both answers by @GeoGyro and @bonzinor solve your problem. You should import qgis.core.edit or you should start/end editing session manually using startEditing and commitChanges . In QGIS Python Console, you don't need import edit method because it is imported by default. Commented Jun 4, 2020 at 10:02

2 Answers 2

3

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

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

from qgis.core import edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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