I needed to add a field to dozens of layers. Some of the layers contained the field already, some of them contained a similar field, and some of them did not have the field. I did not want to batch Add Field, because not only would it fail on the layers which already had the field, but it is super slow and I would then still have to transfer the existing values from the old field to the new field.
|@author Cindy Williams|
|Adds a new field to layers in a map document, based|
|on a current field.|
|For use in the Python window in ArcMap.|
|mxd = arcpy.mapping.MapDocument("CURRENT")|
|lyrs = arcpy.mapping.ListLayers(mxd)|
|# Create a numpy array with a link oid field and the fields to be added|
|narray = numpy.array(, numpy.dtype([('objid', numpy.int), ('GIS_ID', '|S10'),]))|
|for lyr in lyrs:|
|# Find the current field with the values|
|field = [field.name for field in arcpy.ListFields(lyr, "GIS_*")]|
|# Prevent the tool from failing|
|if field != "GIS_ID":|
|# Add the field|
|arcpy.da.ExtendTable(lyr,"OID@", narray, "objid")|
|# Copy the field values to the new field|
|with arcpy.da.UpdateCursor(lyr, ("GIS_ID", field)) as cursor:|
|for row in cursor:|
|row = row|
I wrote the tool in the ArcMap Python window, because I found it easier to load my layers into an mxd first as they were lying all over the place. The new field to be added is set up as a NumPy array, with the relevant dtype.
The script loops over all the layers in the document, adding the field via the Extend Table tool, and then transferring the values from the old field to the new field. Deleting the old field at the end would be an appropriate step to include, but I didn’t, purely because I’ve lost data that way before.