SearchCursor (arcpy)

サマリ

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.

説明

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

A Cursor object that can hand out row objects.

コードのサンプル

SearchCursor example

List field contents for Counties.shp. Cursor sorted by State Name and Population.

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)

関連トピック

9/14/2013