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 Answer 1
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
os.path.basename(fc)
since fc will be the name of a feature class without the path, so fileName=fc