Python Script to Add Fields to Feature Classes
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)
I happen to be doing something similar this morning. This script makes use of the Current Workspace environment variable, listing data, adding a field, and calculating it:
# 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:
...