Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

i´m 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
#Workspace
arcpy.env.workspace="C:\\Users\\xxx.gdb"
# 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! So, any help is welcome and appreciated!

share|improve this question
1  
You might consider using tool validation to avoid running the script tool and finding out the field name the user has entered already exists. The input field parameter will get invalid when user enters an already existing field name. See how to do this: resources.arcgis.com/en/help/main/10.2/index.html#//… –  Alex Tereshenkov Apr 21 at 15:58

1 Answer 1

Alex Tereshenkov'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))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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