3

I have a file GDB living in a network directory with 17 or 18 feature classes. I already created a field I want to populate with the file name of the feature class. Whenever I run my code, it returns

NameError: name 'Washington_PETA' is not defined

This is presumably the first feature class it finds in the GDB. File path altered because there may be sensitive data in it.

Doing this in Python 3 because we're using ArcGIS Pro.

import arcpy, os, sys

arcpy.env.overwriteOutput = True
arcpy.env.workspace = r"R:\filePathHere\feature.gdb"

petas = arcpy.ListFeatureClasses()

for fc in petas:
    print("Updating " + fc)

    inField = "PETA_Name"
    fileName = os.path.basename(fc)
    arcpy.CalculateField_management(fc, inField, fileName, "PYTHON3")

    print(fc + " completed")
  • 1
    Welcome to GIS SE! As a new user, please be sure to take the short tour to learn about this site's focused Q&A format. – Andy Jan 23 at 19:27
  • You dont need to use os.path.basename(fc) since fc will be the name of a feature class without the path, so fileName=fc – BERA Jan 23 at 20:04
5

The Field Calculator expects a quoted string in its expression parameter if you are supplying a simple text string. You can concatenate a pair of double quotes like so: '"' + fileName + '"'.

Your full script would be:

import arcpy, os, sys

arcpy.env.overwriteOutput = True
arcpy.env.workspace = r"R:\filePathHere\feature.gdb"

petas = arcpy.ListFeatureClasses()

for fc in petas:
    print("Updating " + fc)

    inField = "PETA_Name"
    fileName = os.path.basename(fc)
    arcpy.CalculateField_management(fc, inField, '"' + fileName + '"', "PYTHON3")

    print(fc + " completed")
  • 3
    Or "'{0}'".format(fileName) – BERA Jan 23 at 20:03

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.