I am trying to write a simple script for a toolbox, similar to the Addfield_datamanagement toolbox. The script adds a new field to a table of a feature class or a shapefile with attribute tables. So far so good

# Import system modules
import arcpy
# Set feature class
inputFC = arcpy.GetParameterAsText(0)
# Get List of Fieldnames
inputString =arcpy.GetParameterAsText(1)
inputString =arcpy.ValidateFieldName(inputString,arcpy.env.workspace)
fieldList =inputString.split(";")
fieldType = arcpy.GetParameterAsText(2)
for fieldName in fieldList:
          arcpy.AddField_management(inputFC , fieldName, fieldType)
arcpy.AddMessage("Field generated:" + fieldName)
arcpy.AddMessage ("Script executed")

So this seems to work, but now i want to check first if the fieldname already exists before it´s created and print the existing name! I thought about the list fields together with the built-in len() function:

if len(arcpy.ListFields(fieldName(?) or inputString,?)==1:
             arcpy.AddMessage("Field already exists"+fieldName)

Not sure about the synthax of the ListFields command and how to integrate it in the code above!


1 Answer 1


@AlexTereshenkov's comment does bring up a good point; you probably should look into using a validation script for this specific case.

But to answer your question, you should be passing the path (or name) of the feature class, along with an optional wild card and field type to arcpy.ListFields; see the ESRI docs for ListField.

That method actually returns a list of Field objects, which describe the fields (name, type, etc).

So to quickly check to see if a field with the same name exists you could do something like:

existingFields = [f.name for f in arcpy.ListFields(inputFC)]
for fieldName in fieldList:
    if fieldName in existingFields:
        arcpy.AddMessage('Field already exists: %s'%(fieldName))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.