Cursor (arcpy)
Resumen
A cursor is a data access object that can be used either to iterate through the set of rows in a table or to insert new rows into a table. Cursors have three forms: search, insert, or update. Cursors are commonly used to read and update attributes.
Descripción general de los métodos
Método | Explicación |
deleteRow (row) |
Deletes a row in the database. The row corresponding to the current position of the cursor will be deleted. |
insertRow (row) |
Inserts a new row into the database. |
newRow () |
Creates an empty row object. |
next () |
Returns the next object at the current index. |
reset () |
Sets the current enumeration index (used by the next method) back to the first element. |
updateRow (row) |
The updateRow method can be used to update the row at the current position of an update cursor. |
Métodos
Parámetro | Explicación | Tipo de datos |
row |
The row to be deleted. | Row |
Parámetro | Explicación | Tipo de datos |
row |
The row to be inserted. | Row |
Tipo de datos | Explicación |
Object |
The next object at the current index. |
Parámetro | Explicación | Tipo de datos |
row |
The row used to update the current position of the cursor. | Row |
Ejemplo de código
Use search cursor to view field values in row.
import arcpy
from arcpy import env
# Set the workspace
#
env.workspace = "D:/St_Johns/data.gdb"
# Create the search cursor
#
cur = arcpy.SearchCursor("roads", '"TYPE" <> 4')
# Iterate through the rows in the cursor
#
for row in cur:
print "Name: %s, CFCC code: %s" % (row.NAME, row.CFCC)
del cur, row
Use an update cursor to change field values in rows.
import arcpy
from arcpy import env
# Set the workspace
#
env.workspace = "D:/St_Johns/data.gdb"
# Create the update cursor
#
cur = arcpy.UpdateCursor("roads")
# Update the road buffer distance field based on road type.
# Road type is either 1,2,3,4 Distance is in meters.
for row in cur:
row.BUFFER_DIST = row.TYPE * 100
cur.updateRow(row)
# Delete cursor and row objects
#
del cur, row
Use an insert cursor to create new rows in table.
import arcpy
import time
# Create insert cursor for table
#
cur = arcpy.InsertCursor("D:/St_Johns/data.gdb/roads_maint")
x = 1000
# Create 25 new rows. Set default values on distance and CFCC code
#
while x <= 1025:
row = cur.newRow()
row.rowid = x
row.distance = 100
row.CFCC = "A10"
row.LastInsp = time.ctime()
cur.insertRow(row)
x += 1
# Delete cursor and row objects
#
del cur, row