I am trying to create a Python toolbox which will iterate through selected features and create a statistics table for each selected feature.
It works as follow:
- Define parameters, including the input layers with selected features
- Export selected features in new layer
- Use
searchCursor()
to iterate through rows of the new layer - Get row value
- Use row value in an expression to apply
SelectLayerByAttribute()
- Use selected feature to clip another input layer
- Apply some other tools before compute statistics on the other input layer
fc = newLayer
field = "ID_reserve_castor"
cursor = arcpy.SearchCursor(fc)
row = cursor.next()
while row:
value = row.getValue(field)
# Process: Select Layer By Attribute (Select Layer By Attribute) (management)
Reserve_castor_ExportFeature = arcpy.management.SelectLayerByAttribute(
in_layer_or_view=fc,
selection_type="NEW_SELECTION",
where_clause='"ID_reserve_castor" = ' + value,
invert_where_clause="")
row = cursor.next()
The iteration and row.getValue()
work, but not the SelectLayerByAttribute()
.
As the new layer is saved in a geodatabase, I used the exemple mentioned in esri technical support web page.
#Identifies File Geodatabase
if WPtype == "esriDataSourcesGDB.FileGDBWorkspaceFactory.1":
#sample where clause for fgdb data
WhereClause = '"ObjectID" = ' + value
print WhereClause
What did I miss ?
1 Answer 1
As stated by @Vince arcpy.SearchCursor is a legacy tool, and you should be looking at arcpy.da.SearchCursor (unless you only have access to a really old version of ArcMap).
Another suggestion is to hold off on writing the selected features to a new feature class, because you can use a selection directly in a search query and other tools. Writing to a file generally is a bottleneck in the code, and my preference is to save it to the last step.
An example to get you started:
selection = arcpy.management.SelectLayerByAttribute(fc,"NEW_SELECTION",
where_clause='"ID_reserve_castor" = ' + value).getoutput(0)
with arcpy.da.SearchCursor(selection,["SHAPE@"]) as sc:
for row in sc:
feature = row[0]
#you can clip or do something with the shape
If the field you are using in the where clause is string/text, you would need to place the value in single quotes. '"ID_reserve_castor" = ' + "'"+value+"'"
(there is an easier way to do that, but I don't remember if it is available in Python 2.7).
Explore related questions
See similar questions with these tags.
arcpy.SearchCursor
for anything. Instead usearcpy.da.SearchCursor
. If you must manage the selection environment of a layer inside a cursor, make sure it doesn't corrupt the layer on which the cursor is already operating. Best practice is to never nest cursors.