SearchCursor (arcpy)
Récapitulatif
The SearchCursor function establishes a read-only cursor on a feature class or table. The 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.
Discussion
Search cursors are able to 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()
Syntaxe
Paramètre | Explication | Type de données |
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 About_building_an_SQL_expression. | String |
spatial_reference |
When specified, features will be projected on the fly using the spatial_reference provided. | SpatialReference |
fields |
The 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 and D. | String |
Type de données | Explication |
Cursor |
A Cursor object that can hand out row objects. |
Exemple de code
List field contents for Counties.shp. Cursor 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")))