Search if field exists in feature class

Check out this function from by Bjorn Kuiper to test if a field exists :

def FieldExist(featureclass, fieldname):
    fieldList = arcpy.ListFields(featureclass, fieldname)

    fieldCount = len(fieldList)

    if (fieldCount == 1):
        return True
    else:
        return False

with the following example of use:

    if (not FieldExist(myFeatureClass, "myField")):
      arcpy.AddError("Field 'myField' does not exist in " + myFeatureClass)
      sys.exit()

you can use arcpy:

import arcpy

myField = "test"

env.workspace = "D:/test/data.gdb"
fcs = arcpy.ListFeatureClasses()

for f in fcs:
    fieldList = arcpy.ListFields(f)
    for field in fieldList:   
         if field.name == myField:
             print f

Beside this you can use os.walk for files in your drive as:

path = r"C:"
for root, dirs, files in os.walk(path):
    for fileName in files:
            .........

i hope it helps you....


I would prefer a list comprehension instead of string operations (like accepted answer). In my opinion, this is more readable and pythonic. Furthermore, the list comprehension approach could be extended by adding further functionality (str.lower(), like @RyanDalton did) very easy.

def findField(fc, fi):
  fieldnames = [field.name for field in arcpy.ListFields(fc)]
  if fi in fieldnames:
    return "found in " +fc
  else:
    return "not found in " +fc

If you prefer the one liner if-else Statement:

def findField(fc, fi):
  fieldnames = [field.name for field in arcpy.ListFields(fc)]
  return "found in " + fc if fi in fieldnames else "not found in " + fc

Or even Shorter, but less readable:

    def findField(fc, fi):
      return "found in " + fc if fi in [field.name for field in arcpy.ListFields(fc)] else "not found in " + fc