arcpy的da模块提供的SearchCursor用于查询个人地理数据库(.mdb),文件地理数据库(.gdb),属性表(shapefile),以及企业级数据库sde。
使用 SearchCursor 浏览要素类并打印指定字段值和点的 x、y 坐标。
import arcpy
fc = 'c:/data/base.gdb/well'
fields = ['WELL_ID', 'WELL_TYPE', 'SHAPE@XY']
# For each row print the WELL_ID and WELL_TYPE fields, and
# the feature's x,y coordinates
with arcpy.da.SearchCursor(fc, fields) as cursor:
for row in cursor:
print(u'{0}, {1}, {2}'.format(row[0], row[1], row[2]))
使用 SearchCursor 返回一组唯一字段值。
import arcpy
fc = 'c:/data/base.gdb/well'
field = 'Diameter'
# Use SearchCursor with list comprehension to return a
# unique set of values in the specified field
values = [row[0] for row in arcpy.da.SearchCursor(fc, field)]
uniqueValues = set(values)
print(uniqueValues)
使用 SearchCursor 返回使用令牌的属性。
import arcpy
fc = 'c:/data/base.gdb/well'
# For each row, print the Object ID field, and use the SHAPE@AREA
# token to access geometry properties
with arcpy.da.SearchCursor(fc, ['OID@', 'SHAPE@AREA']) as cursor:
for row in cursor:
print('Feature {} has an area of {}'.format(row[0], row[1]))
使用 SearchCursor 与 where 子句识别满足特定条件的要素。
import arcpy
fc = 'c:/base/data.gdb/roads'
class_field = 'Road Class'
name_field = 'Name'
fields = [class_field, name_field]
# Create an expression with proper delimiters
expression = u'{} = 2'.format(arcpy.AddFieldDelimiters(fc, name_field))
# Create a search cursor using an SQL expression
with arcpy.da.SearchCursor(fc,fields,where_clause=expression) as cursor:
for row in cursor:
# Print the name of the residential road
print(row[1])
使用 SearchCursor 和 Python 的排序方法对行排序。有关其他排序选项,请参阅 Python 的如何实现最短排序。
import arcpy
fc = 'c:/data/base.gdb/well'
fields = ['WELL_ID', 'WELL_TYPE']
# Use Python's sorted method to sort rows
for row in sorted(arcpy.da.SearchCursor(fc, fields)):
print(u'{0}, {1}'.format(row[0], row[1]))
或者,如果数据支持 SQL ORDER BY,则使用 sql_clause 进行排序。
import arcpy
fc = 'c:/data/base.gdb/well'
fields = ['WELL_ID', 'WELL_TYPE']
# Use ORDER BY sql clause to sort field values
for row in arcpy.da.SearchCursor(
fc, fields, sql_clause=(None, 'ORDER BY WELL_ID, WELL_TYPE')):
print(u'{0}, {1}'.format(row[0], row[1]))
使用 SQL TOP 限制要返回的记录数。
import arcpy
fc = 'c:/data/base.mdb/well'
fields = ['WELL_ID', 'WELL_TYPE']
# Use SQL TOP to sort field values
for row in arcpy.da.SearchCursor(fc, fields, sql_clause=('TOP 3', None)):
print(u'{0}, {1}'.format(row[0], row[1]))