Saturday 20 July 2019

arcgis 10.0 - Search if field exists in feature class


I have a few dozen feature classes, one of which contains the field I am looking for. They are stored in several different file geodatabases.



Is there a quick way of searching each feature class to find the one that has my field? Or do I have to check each one's attribute table in Catalog? Some of the files have the same names but are stored in separate locations.


I would like to be able to do this inside a Calculate Value tool in ModelBuilder, so that each time I needed to, I could run the model on a single file gdb and it would search through all the feature classes within that gdb and look for the field.


So far, I have a feature class iterator which iterates over all the feature classes in the file gdb recursively. Inside the Calculate Value I have the following code:


findField(r"%Feature%", "%Search Field%")



def findField(fc, fi):
lst = arcpy.ListFields(fc)
for f in lst:
if f.name == fi:

return fc
else:
return "not found"

The returned values are collected in Output Values as strings. The output for all the feature classes has been "not found", even though the field exists in at least 4 of them. enter image description here



Answer



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

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...