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(inputFC,?)==1: #not sure if inputFC is right?
arcpy.AddMessage("Field already exists"+fieldName)
Not sure about the syntax of the ListFields
command and how to integrate it in the code above! So, any help is welcome and appreciated!
ListFields
returns a list
of field objects, and each of these objects has attributes associated with it.
So the structure looks like this:
field_list = [field object1: field.name, field.type, etc...;
field object2: field.name, field.type, etc...;
]
You'll probably want to access the .name
attribute of each field object to determine if it matches any name in the variable fieldList
.
First, generate a list of field names:
existingFields = [] # empty list
for field in arcpy.ListFields(inputFC): # iterate over fields
existingFields.append(field.name) # add the attribute name to list for each field
Next, compare the list of existing fields with the list of fields the user wants to add:
duplicateFields = set(existingFields) & set(fieldList)
if len(duplicateFields) == 0:
carry on with adding fields
else:
arcpy.AddMessage('Field(s) already exist: ' + duplicateFields)