[GIS] How to add multiple fields to many Feature class using Arcpy

arcpyesri-geodatabasefeature-classloop

I have a geodatabase with multiple Feature Class (at least 100).

I would like to add in each attribute table of each Feature Class, two new columns. I have to do that with a python script because it would be very long to add the columns one by one.
The two new columns are : "symbole" and "deslotID".

I try to make a python script, but I don't know anything about python.
This is the code (I know it don't works)

>>> import arcpy
from arcpy import env

#My environment and the geodatabase that contains the feature class
env.workspace = "C:/data/arcgis/gdb/Featureclass.gdb"

#Set fieldname variables = 2 new columns
field_name1 = "symbole"
field_name2 = "deslotID"

#Define the fields's structure
fields = [
("featureclass", "field_name1", "LONG", 9, "", "", "refcode", "NULLABLE", "NON_REQUIRED")
("featureclass", "field_name2", "INT", 9, "", "", "refcode", "NULLABLE", "NON_REQUIRED")
]

for field in fields:
    arcpy.AddField_management(*(featureclass,) + field)

For this code, I was inspired by this question : Possible to add multiple fields in single arcpy statement?

I think I have to make a loop that runs through all the feature class in the geodatabase, I really don't know how to do that.

Best Answer

The code you require is below:

import arcpy

# Set workspace
arcpy.env.workspace = r"C:\Scratch\fGDB_Scratch.gdb"

# This returns a list of FeatureClasses in the top level of the geodatabase
fcl = arcpy.ListFeatureClasses("*")

# Main loop
for fc in fcl:
    print "Adding fields to " + fc

    # The "#" inputs mean just use defaults
    arcpy.AddField_management(fc,"symbole", "LONG", "#", "#", "#", "symbole", "NULLABLE", "NON_REQUIRED")
    arcpy.AddField_management(fc,"deslotID", "LONG", "#", "#", "#", "deslotID", "NULLABLE", "NON_REQUIRED")

print "Finished!"

I would recommend you look at the ListFeatureClasses() method to understand how you get lists of FeatureClasses. This works as the workspace environment setting for arcpy had been set.