UpdateCursor

摘要

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

说明

旧版本:

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

可用于迭代更新游标的方式有两种: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

包含要更新或删除行的要素类、shapefile 或表。

String
where_clause

用于限制在游标中返回的行的可选表达式。有关 where 子句和 SQL 语句的详细信息,请参阅在 ArcGIS 中使用的查询表达式的 SQL 参考

String
spatial_reference

在提供的 spatial_reference 中指定的坐标,并动态转换到数据集的坐标系。

SpatialReference
fields

游标中包含以分号分隔的字符串字段。默认情况下,包含所有字段。

String
sort_fields

用于在游标中对行进行排序的字段。每个字段的升序和降序排列表示为 A 形式,D 表示升序,"field1 A;field2 B" 表示降序。

String
返回值
数据类型说明
Cursor

可分发 Row 对象的 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

相关主题