How can I check to see if an attribute field exists using ArcPy?

Something I get asked in virtually every “Introduction to geoprocessing scripts using Python” course is:

Using Python and ArcPy, how do I know if an attribute field exists?”.

This is an important question to ask if you are data-loading into an existing dataset using an Update Cursor or writing to a brand new dataset using an Insert Cursor because you may need to make sure that, at the very least, a particular attribute field exists or you may need to make a new one to support some data loading of attribute data.

In the ArcPy site package there is no “FieldExists()” function.…. so how do you determine whether an attribute field exists in a dataset?

Possibly the best way is to use a combination of the arcpy.ListFields() function, and count the length of the resulting list.

When you inspect the documentation for the arcpy.ListFields() function, you will see that it returns a Python list of field objects. You will also see that it has an optional wildcard argument. This allows you to find all those attribute fields beginning with or containing the specified search string.

To see if an attribute field exists you should add the full name of the field as the wildcard. If the resulting list has exactly one item inside it then you know the field is present within your table or feature class. If the list is empty then the wild card has not found the attribute field in the dataset which means the field does not exist.

Let’s see how this works in a code sample. I want to find out if the ST_NAME field exists in the Address feature layer as presented below:


If the field does not exist then create a new field using the Add Field geoprocessing tool. If it does exist then great! The script can continue to execute.

# Check to see if the ST_NAME attribute field exists
import arcpy
arcpy.env.workspace = r”C:\Student\PYTH\Database\corvallis.gdb”
fields = arcpy.ListFields(“Address”, “ST_NAME”)
if len(fields) != 1:
    arcpy.AddField_management(“Address”, “ST_NAME”, “TEXT”)

# Perform rest of script workflow once field is present…

And there you have it…!


2 thoughts on “How can I check to see if an attribute field exists using ArcPy?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s