Select to view content in your preferred language

if field.name in fieldList

1671
3
Jump to solution
09-23-2014 12:42 AM
BenLeslie1
Frequent Contributor

Hi

I'm trying to do a script that will search a bunch of features and tell me if they contain a certain field name or not:

fcs = arcpy.ListFeatureClasses()

for fc in fcs:

     fieldList = arcpy.ListFields(fc)

     if "CAT" in fieldList:

          print fc + " Yes"

     else:

          print fc + " Nope"

I think I've figured out that I somehow need to tell it is look for "CAT" as a field name in fieldList but I'm not sure how to write it.

I've tried a few things such as:

     if "CAT" in fieldList.field.name

but I haven't hit upon the correct syntax.

Can you help?

(just thought I'd add that everything comes out as "Nope", which isn't correct, using the above code)

0 Kudos
1 Solution

Accepted Solutions
AnthonyGiles
Honored Contributor

Ben,

The best way would be to to create a boolean variable that you set to true if the field name exists, something like:

for fc in fcs:

  fieldList = arcpy.ListFields(fc)

  fieldExists = false 

     for field in fieldList:

        if field.name == "CAT":

          fieldExists = true

  if(fieldExists):

    print fc + " Yes"

  else:

    print fc + " No"

View solution in original post

3 Replies
AnthonyGiles
Honored Contributor

Ben,

You need to iterate through each of your fields checking them individually, not tested but something like:

for fc in fcs:

  fieldList = arcpy.ListFields(fc)

     for field in fieldList:  

        if field.name == "CAT":

          Do Something.....

        else:

          Do Something....

0 Kudos
BenLeslie1
Frequent Contributor

Thanks Anthony but it doesn't quite give me the results I'm looking for..... your answer tells me whether every fieldname in the list is "CAT" or not so the output is:

feature1.shp Nope

feature1.shp Nope

feature1.shp Yes

feature1.shp Nope

feature2.shp Nope

feature2.shp Nope

feature2.shp Nope

feature2.shp Nope

........etc

What I really want is a single yes or no for each feature.

For each feature could I somehow concatenate all the fieldnames into a single string and test that?

0 Kudos
AnthonyGiles
Honored Contributor

Ben,

The best way would be to to create a boolean variable that you set to true if the field name exists, something like:

for fc in fcs:

  fieldList = arcpy.ListFields(fc)

  fieldExists = false 

     for field in fieldList:

        if field.name == "CAT":

          fieldExists = true

  if(fieldExists):

    print fc + " Yes"

  else:

    print fc + " No"