Why is this for loop returning empty shapefiles?

299
2
07-06-2022 02:00 PM
Labels (1)
rescobar
New Contributor III

Hello, 

I am working on script to loop through three counties and create layers of the cities contained in each by means of a where clause. My script below will work if instead of a for loop, I just put one county into the where clause. However, when I execute this in pro, it returns three blank county layers. Is there something wrong with my formatted string in the where clause?

 

cities = r"E:\Users\Documents\ArcGIS\Projects\Practice\Practice.gdb\incorpcity"

counties = r"E:\Users\Documents\ArcGIS\Projects\Practice\Practice.gdb\Countygdb"


outpath = r"E:\Users\Documents\ArcGIS\Projects\Practice\Practice.gdb"


arcpy.env.overwriteOutput = True


counties_of_interest = ['Contra Costa County', 'Alameda County', 'Solano County']



arcpy.management.MakeFeatureLayer(cities, 'cities_temp')



for county in counties_of_interest:
    arcpy.management.MakeFeatureLayer(counties, 'counties_temp', """ COUNTY_NAME = '{}' """.format(county))



    arcpy.management.SelectLayerByLocation('cities_temp', 'WITHIN', 'counties_temp')


    county_1 = county.replace(" ", "_")
    arcpy.conversion.FeatureClassToFeatureClass('cities_temp', outpath, f'cities_{county_1}')

 

Tags (2)
0 Kudos
2 Replies
DavidSolari
Occasional Contributor III

It's a bit hard to diagnose this from where I'm sitting, your code looks solid overall. One thing you can do is modify the loop to print out the generated SQL clauses and see what happens if you try to set a definition query with them, then select them by location etc. etc. That way you can see where the process breaks down interactively. If everything works just fine this way then I'm not sure what the next step would be. Maybe try replacing arcpy.conversion.FeatureClassToFeatureClass with arcpy.analysis.Select?

0 Kudos
HannesZiegler
Esri Contributor

@rescobar I tried this and I got the expected results. What release of ArcGIS Pro are you using?

0 Kudos