Select by attribute and location within a for loop?

arcpyfor loopintersectselect-by-attributeselect-by-location

I have dozens of feature classes in a project geodatabase. I have the code that will identify all the misplaced wells in each dataset, but for the life of me I can't figure out how to get the lines of code into a for loop. I need to run each one through this process to get the output I need:

 1. arcpy.management.SelectLayerByAttribute("Counties", "NEW_SELECTION", "NAME = 'CountyName'", "NON_INVERT")
 2. arcpy.management.SelectLayerByLocation("CountyName_WaterWells", "INTERSECT", "Counties", None, "NEW_SELECTION", "INVERT")
 3. arcpy.management.CopyFeatures("CountyName_WaterWells", r"C:\Users\UserName\Documents\ArcGIS\Projects\Water Well Outliers Script\Water Well Outliers Script.gdb\CountyName_WaterWells_Outliers", '', None, None, None)

"Counties" is my polygon feature class, "CountyName_WaterWells" are my water well feature classes, "NAME" is the field name for "CountyNames" in the "Counties" feature class.

I can just keep using these lines of code and replace the county names, but then I'd have over 250 lines of code.

Best Answer

One option is to use ListFeatureClasses() which will provide a list of the feature classes in the workspace. Assuming the feature classes are all in the same geodatabase, you can set the workspace to your geodatabase. Something else that might help is to chain the selections and capture the output of the previous selection so you can use it later.

Something along these lines:

arcpy.env.workspace = r"C:\Users\UserName\Documents\ArcGIS\Projects\Water Well Outliers Script\Water Well Outliers Script.gdb"
fcs = arcpy.ListFeatureClasses("*_WaterWells")
for fc in fcs:
    countyName = fc.split("_")[0] #assuming that the feature classes all have the same pattern
    sel_counties = arcpy.management.SelectLayerByAttribute("Counties", "NEW_SELECTION", "NAME = '{}'".format(countyName), "NON_INVERT").getOutput(0)
    sel_wells = arcpy.management.SelectLayerByLocation(fc, "INTERSECT", sel_counties, None, "NEW_SELECTION", "INVERT").getOutput(0)
    arcpy.management.CopyFeatures(sel_wells, "{}_WaterWells_Outliers".format(countyName), '', None, None, None)