I have an ArcPy script that adds new fields and then deletes unnecessary fields from a group of feature classes. I am a novice at ArcGIS and even more so at ArcPy, but have been able to piece together the code below from other working examples. I am currently using ArcGIS 10.0, and expect to get version 10.3 before long.
import arcpy, os try: # Set the workspace to edit arcpy.env.workspace = r'E:\Python Testing\NavajoAUM_SiteScreens.gdb\Central' # For loop to go through feature classes in the workspace for fc in arcpy.ListFeatureClasses(): # add new fields arcpy.AddField_management(fc, "GammaMeas", "DOUBLE", field_precision = 9, field_scale = 0) arcpy.AddField_management(fc, "BkgLevel", "DOUBLE", field_precision = 9, field_scale = 0) arcpy.AddField_management(fc, "MineID", "TEXT", field_length = 10) arcpy.AddField_management(fc, "OrigFileName", "TEXT", field_length = 50) # Set the cursor cursor = arcpy.UpdateCursor(fc) row = cursor.next() # Save values for the MineID and OrigFileName desc = arcpy.Describe(fc) mineValue = desc.name[desc.name.rfind("_") + 1:] fileValue = desc.name # While loop updates values in each row while row: row.setValue("GammaMeas", row.getValue("Text")) row.setValue("BkgLevel", "12500") row.setValue("MineID", mineValue) row.setValue("OrigFileName", fileValue) cursor.updateRow(row) row = cursor.next() except: pass # Set the workspace to edit arcpy.env.workspace = r'E:\Python Testing\NavajoAUM_SiteScreens.gdb\Central' # Local Variables to keep keep = ['OBJECTID','FID','Shape', 'Text', 'Channel', 'Northing', 'Easting', 'GammaMeas', 'BkgLevel', 'MineID', 'OrigFileName'] # be SURE to include FID/OBJECTID field here! for fc in arcpy.ListFeatureClasses(): try: discard =  for field in [f.name for f in arcpy.ListFields(fc)if f.type <> 'Geometry']: if field not in keep: discard.append(field) arcpy.DeleteField_management(fc, discard) except: pass
It seems like using memory management would greatly improve the performance of the script, and that error handling could be improved, but I'm at a loss on how to implement either of those correctly here. There might be other obvious improvements to make that I don't know about, or haven't attempted yet (e.g., maybe adding fields and deleting fields in one loop would be better).
As far as errors go, it appears that sometimes the script runs fine, sometimes it will throw an error and stop, and other times no error is raised but the script seems to stop early (e.g., not all fields added or filled, no fields deleted). I'd like to know where / which feature classes are causing the errors so I can QC the feature class / attributes table and fix.