2

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
#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!

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Apr 21, 2014 at 15:27
0

1 Answer 1

5

@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))
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
answered Apr 21, 2014 at 16:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.