UpdateCursor (arcpy)

摘要

UpdateCursor 函数创建一个用于更新或删除指定要素类、shapefile 和表中的行的游标。该游标将数据锁定保留至脚本完成或更新游标对象被删除时。

讨论

以迭代方式更新游标的方式有两种:for 循环或者 while 循环(通过游标的 next 方法返回下一行)。如果要使用游标的 next 方法来检索行数为 N 的表中的所有行,脚本必须调用 next N 次。在检索完结果集的最后一行后调用 next 将返回 None,它是一种 Python 数据类型,此处用作占位符。

通过 for 循环使用 UpdateCursor

import arcpy

fc = "c:/data/base.gdb/roads"
field1 = "field1"
field2 = "field2"

cursor = arcpy.UpdateCursor(fc)
for row in cursor:
    # field2 will be equal to field1 multiplied by 3.0
    row.setValue(field2, row.getValue(field1) * 3.0)
    cursor.updateRow(row)

通过 while 循环使用 UpdateCursor

import arcpy

fc = "c:/data/base.gdb/roads"
field1 = "field1"
field2 = "field2"

cursor = arcpy.UpdateCursor(fc)
row = cursor.next()
while row:
    # field2 will be equal to field1 multiplied by 3.0
    row.setValue(field2, row.getValue(field1) * 3.0)
    cursor.updateRow(row)
    row = cursor.next()

语法

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

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

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

Coordinates are specified in the spatial_reference provided and converted on the fly to the coordinate system of the dataset.

SpatialReference
fields
[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

游标对象可分发行对象。

代码实例

UpdateCursor 示例

根据另一个字段值更新要素类中的字段值。

import arcpy

# Create update cursor for feature class
rows = arcpy.UpdateCursor("c:/data/base.gdb/roads")

# Update the field used in buffer so the distance is based on the
# road type. Road type is either 1, 2, 3 or 4. Distance is in meters.
for row in rows:
    # Fields from the table can be dynamically accessed from the
    # row object. Here fields named BUFFER_DISTANCE and ROAD_TYPE
    # are used
    row.setValue("BUFFER_DISTANCE", row.getValue("ROAD_TYPE") * 100)
    rows.updateRow(row)

# Delete cursor and row objects to remove locks on the data
del row
del rows

相关主题

5/10/2014