Check for existence of a field

32492
9
08-03-2011 08:07 AM
MikeDriver
New Contributor II
How do you check for the existence of a field in a feature class?  v10.
I did this, but it seems clunky.

import arcpy
fc = r"C:\temp\test.shp"
desc = arcpy.Describe(fc)
flds = desc.fields
fldin = 'no'
for fld in flds:
   if fld.name == 'USNG':
        fldin = 'yes'

print fldin
Tags (2)
9 Replies
MikeDriver
New Contributor II
Lines:
if fld.name == 'USNG':
fldin = 'yes'

should be indented, of course.
0 Kudos
JakeSkinner
Esri Esteemed Contributor
Your code will work with no problems.  You can also use the 'arcpy.ListFields' function.  Ex:

lstFields = arcpy.ListFields(fc)

x = False

for field in lstFields:
    if field.name == "USNG":
        print "Field exists"
        x = True

if x <> True:
    print "Field does not exist"


I tested the Describe function vs the ListFields function using the time module, and the ListFields function was slightly faster by a tenth of a second.

Also, to preserve indentation when copying/pasting your code, select your code and click the '#' button at the top.  It will wrap it in CODE tags.
StacyRendall1
Occasional Contributor III
lstFields = arcpy.ListFields(fc)

if "USNG" in lstFields:
    print "Field exists"
else:
    print "Field does not exist"


Not sure if there is any speed difference... The 'in' thing is pretty handy for checking if something is in a list - in this case the ListFields is a list. For example:
>>> a = [3,5,6,'kitty']   # a Python list
>>> b = 2
>>> b in a
False
>>> c = 5
>>> c in a
True
>>> d = 'kitty'
>>> d in a
True
>>> 
TylerCovington
New Contributor

This is the most direct. Your code is so clear and concise. Well done!

0 Kudos
curtvprice
MVP Esteemed Contributor

Stacy's arcpy.ListFields returns a list of field objects (not field names) so the "in" operator would not work. You could make it work by converting the list to field names (and converting to upper case because the in operator is case sensitive). 

lstFields = arcpy.ListFields(fc)
field_names = [f.name.upper() for f in lstFields]
if "USNG" in field_names:
    print "Field exists" 
else: 
    print "Field does not exist"‍‍‍‍‍‍
Brownschuh
Occasional Contributor II

Tested Stacy's code above and curtvprice is correct, the "in" operator will not work.

0 Kudos
MikeDriver
New Contributor II
Thanks all!
0 Kudos
curtvprice
MVP Esteemed Contributor
An empty list evaluates to False so here's the way I do it:

if arcpy.ListFields(tbl, field_name):
     print "Field exists"
else:
     print "Field doesn't exist"


It should be noted that AddField_management does not fail if you add a field that exists already, it just prints a warning and doesn't do anything. (Makes for less complicated ModelBuilder models.)
Brownschuh
Occasional Contributor II

This code worked for me.  Using a couple for loops I was able to run this against multiple feature classes within multiple feature datasets to determine if a field was present.