SearchCursor

摘要

从要素类或表中返回属性值行。

SearchCursor 函数遍历 Row 对象并提取字段值。

说明

旧版本:

自 ArcGIS 10.1 起,此功能已由 arcpy.da.SearchCursor 取代。 为了获得更快性能,请使用 arcpy.da.SearchCursor

可用于迭代搜索游标的方式有两种: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))
    row = cursor.next()

语法

SearchCursor (dataset, {where_clause}, {spatial_reference}, {fields}, {sort_fields})
参数说明数据类型
dataset

The feature class, shapefile, or table containing the rows to be searched.

String
where_clause

An 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
返回值
数据类型说明
Cursor

可分发 Row 对象的 Cursor 对象。

代码示例

SearchCursor 示例

列出 Counties.shp 的字段内容。 游标按州名称和人口进行排序。

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")))

相关主题