Hi,
I wrote a few lines of Python code to add a set of fields if they are not already present in a feature layer. Here is my code.
# Import modules import arcpy input_table = "myFeatureLayer" # Input fields to create if they are not present in the feature layer input_fields = ["a", "b", "c", "d", "e", "f", "g"] # Field type attr_type = "SHORT" for field in input_fields: if len(arcpy.ListFields(input_table, wild_card=field)) == 0: arcpy.AddField_management(input_table, field_name = field, field_type = attr_type)
Sometimes it runs through the first 3 fields on the list before raising an error and sometimes it only goes through 1 or 2 fields. There are couple of times when the whole code ran without issue and created the entire list of fields.
This is the error I get:
Runtime error Traceback (most recent call last): File "<string>", line 13, in <module> File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\management.py", line 3246, in AddField raise e ExecuteError: ERROR 999999: Error executing function. Failed to execute (AddField).
Any suggestions or thoughts on what the issue might be?
Thanks,
Theja
Solved! Go to Solution.
you need to set your work environment for one thing, the layer name isn't sufficient, check the example
you need to set your work environment for one thing, the layer name isn't sufficient, check the example
Thanks Dan!
That worked! I was using this in a tool earlier and the environment workspace that was set for the tool was different from the shapefile location.
I am still not very clear on why it works for the first one or two fields before raising an error.
I think what you probably want to do is make sure that the field doesn't already exist. However, when you use ListFields, it returns a field object, from which you have to get its name and check to make sure it isn't in there.
I then would check the fields that you want to add ( ie your_fields in my example below) and see if they are 'in' the list of fields (via their name) that already are in there.
from here... ListFields—Help | ArcGIS for Desktop
featureclass = "c:/data/municipal.gdb/hospitals"
field_names = [f.name for f in arcpy.ListFields(featureclass)]
for fld in your_fields:
if fld in field_names:
print("this field {} exists already".format(fld))
else:
then proceed with adding the field as you have done