SearchCursor (arcpy)
摘要
SearchCursor 函数用于在要素类或表上建立只读游标。SearchCursor 可用于遍历行对象并提取字段值。可以使用 where 子句或字段限制搜索,并对结果排序。
讨论
以迭代方式搜索游标的方式有两种:for 循环或者 while 循环(通过游标的 next 方法返回下一行)。如果要使用游标的 next 方法来检索行数为 N 的表的所有行,脚本必须调用 next N 次。在检索完结果集的最后一行后再调用 next 将返回 None,它是一种 Python 数据类型,此处用作占位符。
通过 for 循环使用 SearchCursor。
import arcpy
fc = "c:/data/base.gdb/roads"
field = "StreetName"
cursor = arcpy.SearchCursor(fc)
for row in cursor:
    print(row.getValue(field))
通过 while 循环使用 SearchCursor。
import arcpy
fc = "c:/data/base.gdb/roads"
field = "StreetName"
cursor = arcpy.SearchCursor(fc)
row = cursor.next()
while row:
    print(row.getValue(field))
    cursor.next()
语法
| 参数 | 说明 | 数据类型 | 
| 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. | Object | 
| 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 | 
| 数据类型 | 说明 | 
| Cursor | 游标对象可分发行对象。 | 
代码实例
列出 Counties.shp 的字段内容。游标按“州名称”和“人口”排序。
import arcpy
# Open a searchcursor 
#  Input: C:/Data/Counties.shp 
#  FieldList: NAME; STATE_NAME; POP2000 
#  SortFields: STATE_NAME A; POP2000 D 
# 
rows = arcpy.SearchCursor("c:/data/counties.shp", "", "", "NAME; STATE_NAME; POP2000", 
                          "STATE_NAME A; POP2000 D") 
currentState = "" 
# Iterate through the rows in the cursor 
# 
for row in rows: 
    if currentState != row.STATE_NAME: 
        currentState = row.STATE_NAME 
    # Print out the state name, county, and population 
    # 
    print "State: %s, County: %s, population: %i" % \
            (row.STATE_NAME, row.NAME, row.POP2000)