I have to try to add a field called 'Name' to a bunch of different feature classes using python, and then access the name of the feature class to fill in the field. I have no idea how to even start this! I know I need a loop but that's all I know.
Answer
Here is a cursor-based approach, which I usually default to as syntax is simpler than using Calculate Field. This is the workflow:
import your module
import arcpy
Set the workspace so that Python knows where to look for the feature classes. In this case, it is a GDB
arcpy.env.workspace = r'C:\temp2\my_gdb.gdb'
Start a loop and iterate over the feature classes in the GDB
for fc in arcpy.ListFeatureClasses():
Add a text field called "Name" of length 50
arcpy.AddField_management(fc, "Name", "TEXT", field_length = 50)
Within each feature class attribute table, write the name of the current FC
with arcpy.da.UpdateCursor(fc, "Name") as cursor:
for row in cursor:
row[0] = fc
cursor.updateRow(row)
import arcpy
arcpy.env.workspace = r'C:\temp2\my_gdb.gdb'
for fc in arcpy.ListFeatureClasses():
arcpy.AddField_management(fc, "Name", "TEXT", field_length = 50)
with arcpy.da.UpdateCursor(fc, "Name") as cursor:
for row in cursor:
row[0] = fc
cursor.updateRow(row)
No comments:
Post a Comment