Zusammenfassung
The SearchCursor function establishes a read-only cursor on a feature class or table. SearchCursor can be used to iterate through Row objects and extract field values. The search can optionally be limited by a where clause or by field and optionally sorted.
Diskussion
Vorversion:
This function was superceded by arcpy.da.SearchCursor at ArcGIS 10.1. For faster performance, use arcpy.da.SearchCursor.
Search cursors can be iterated with a for loop or in a while loop using the cursor's next method to return the next row. When using the next method on a cursor to retrieve all rows in a table containing N rows, the script must make N calls to next. A call to next after the last row in the result set has been retrieved returns None, which is a Python data type that acts here as a placeholder.
Using SearchCursor with a for loop.
import arcpy
fc = "c:/data/base.gdb/roads"
field = "StreetName"
cursor = arcpy.SearchCursor(fc)
for row in cursor:
print(row.getValue(field))
Using SearchCursor with a while loop.import arcpy
fc = "c:/data/base.gdb/roads"
field = "StreetName"
cursor = arcpy.SearchCursor(fc)
row = cursor.next()
while row:
print(row.getValue(field))
row = cursor.next()
Syntax
SearchCursor (dataset, {where_clause}, {spatial_reference}, {fields}, {sort_fields})
Parameter | Erläuterung | Datentyp |
dataset | The feature class, shapefile, or table containing the rows to be searched. | String |
where_clause | An optional expression that limits the rows returned in the cursor. For more information on where clauses and SQL statements, see Write a query in the query builder. | String |
spatial_reference | When specified, features will be projected on the fly using the spatial_reference provided. | SpatialReference |
fields | A semicolon-delimited string of fields to be included in the cursor. By default, all fields are included. | String |
sort_fields | Fields used to sort the rows in the cursor. Ascending and descending order for each field is denoted by A for ascending and D descending, using the form "field1 A;field2 D". | String |
Datentyp | Erläuterung |
Cursor | A Cursor object that can hand out Row objects. |
Codebeispiel
List field contents for Counties.shp. Cursor is sorted by state name and population.
import arcpy
# Open a searchcursor
# Input: C:/Data/Counties.shp
# Fields: NAME; STATE_NAME; POP2000
# Sort fields: STATE_NAME A; POP2000 D
rows = arcpy.SearchCursor("c:/data/counties.shp",
fields="NAME; STATE_NAME; POP2000",
sort_fields="STATE_NAME A; POP2000 D")
# Iterate through the rows in the cursor and print out the
# state name, county and population of each.
for row in rows:
print("State: {0}, County: {1}, Population: {2}".format(
row.getValue("STATE_NAME"),
row.getValue("NAME"),
row.getValue("POP2000")))