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.
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
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 = 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 = fc cursor.updateRow(row)
# set workspace environment to your GDB arcpy.env.workspace = r"C:\junk\db.gdb" # list the feature classes fcList = arcpy.ListFeatureClasses() # loop through list for fc in fcList: #check if field exists, if not, add it and calculate if "VALUE" not in arcpy.ListFields(fc): arcpy.AddField_management(fc,"VALUE","TEXT") arcpy.CalculateField_management(fc,"VALUE",fc)
Given the multiple answers using ListFeatureClasses() just wanted to add that if you have feature classes in feature datasets in your geodatabase you will need to add one extra loop to handle those feature classes.
fds = arcpy.ListDatasets() for fd in fds: fcs = arcpy.ListFeatureClasses(feature_dataset=fd) for fc in fcs: ... fcs = arcpy.ListFeatureClasses() for fc in fcs: ...
You were correct about the loop! You can use a loop to work through each feature class in the current workspace.
featureClasses = arcpy.ListFeatureClasses(): for fc in featureClasses: arcpy.AddField_management(fc,"Name","TEXT")
That would create a text field called "Name" in each feature class in your current workspace.
I would need a bit more information to help with the filling in part.
Does each feature class have features in it? how many? Does each feature get a different name?