I am trying to iterate through a feature layer of counties, using each row as the selection expression for Select by Attribute. This selection will then be used to clip another layer. The goal is to break the initial layer into smaller pieces to aid in geoprocessing.
`import arcpy
counties = arcpy.MakeFeatureLayer_management(r"R:\Data\Base_Data\Administrative\Admin_Political_Bounds.gdb\HL_Political_Boundaries\HL_Counties_NJGIN", "counties")
workspace = r"R:\Data\Data_Development\HDC_Allocations\HDC_raw3.gdb"
with arcpy.da.SearchCursor(counties, ['SHAPE@AREA','COUNTY']) as cursor:
for row in cursor:
i=row[1]
expression = '"COUNTY" = {0}'.format(i)
county = arcpy.SelectLayerByAttribute_management(counties,"NEW_SELECTION", expression)
outname = workspace + "_" + row[1]
arcpy.Clip_analysis(HDC_raw, county, outname)
arcpy.Delete_management(county)`
My problem is that I keep getting a syntax/invalid expression error on the Select Layer by Attribute line.
This is part of a much larger script that is run as a standalone script.
2 Answers 2
Use AddFieldDelimiters and if COUNTY is a string/text field you are missing single quotes around the value:
expression = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(datasource="counties", field="COUNTY"), i)
And counties
is a result object, "counties"
is the layer which you should be using in SelectLayerByAttributes
arcpy.SelectLayerByAttribute_management(in_layer_or_view="counties", selection_type="NEW_SELECTION", where_clause=expression)
The Split tool is the correct way of doing this. It takes the file that you want to split and splits it according to the features in a separate file. In this case, it takes my target layer and splits it by county, located in a separate layer.
http://desktop.arcgis.com/en/arcmap/10.3/tools/analysis-toolbox/split.htm
counties
is a result object,"counties"
is the layer which you should be using in SelectLayerByAttributesr"R:\Data\Base_Data\Administrative\Admin_Political_Bounds.gdb\HL_Political_Boundaries\HL_Counties_NJGIN"
) or layer (e.g. "counties"), butSelectByAttributes
requires the layer ("counties"
). As BERA pointed outcounties
is a result object based on the creation of the featurelayer, but is not the actual layer name.