# 2.3.shapefile更新

更新shapefile使用的是`arcpy.da.UpdateCursor`函数，UpdateCursor 能够对游标所访问的数据进行读写，其定义如下：

```
UpdateCursor(in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause})
```

参数的意义与`arcpy.da.SearchCursor`相同。

> `UpdateCursor`具有四个方法：
>
> `deleteRow()`：删除当前要素
>
> `next()`：用于迭代时获取下一行数据
>
> `reset()`：将游标重置到第一行
>
> `updateRow(row)`：更新当前行数据

接下来来看一段代码：

```
shp_file_path = ur'../data/ReadData/Point.shp'
fields_array = ['SHAPE@', 'Id']
# 定义WGS84坐标系
spatial_reference = arcpy.SpatialReference(4326)
with arcpy.da.UpdateCursor(shp_file_path, fields_array, spatial_reference=spatial_reference) as cursor:
    row_index = 0
    for row in cursor:
        if row_index == 0:
            new_id = random.randint(1, 100)
            row[1] = new_id
        else:
            new_y = random.randint(-90, 90)
            old_pt = row[0].firstPoint
            row[0] = arcpy.Point(old_pt.X, new_y)
        row_index += 1
        cursor.updateRow(row)
```

这段代码是更新了一个“Point.shp”文件。开始，我们定义了需要搜索的字段为\['SHAPE@', 'Id']，当`row_index == 0`时，更改了属性中的第2个字段——Id——为一个随机整数；当`row_index == 1`时，更改了属性中的第1个字段——几何信息，此处为点——的y坐标为一个在\[-90,90]之间的随机整数。

注意：根据图层类型的不同，当更新几何信息时，所构建的几何对象也不同，这一点和添加要素时是一致的，具体请看上一节。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zxyao.gitbook.io/arcpy/2.3.shapefile-geng-xin.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
