Arcpy implements query, insert, update and delete on the attribute table of the layer file

foreword

To add, delete, modify and query the attribute table, you need to use the insert cursor, delete cursor, update cursor, and query cursor.

The official document address is as follows: https://resources.arcgis.com/zh-cn/help/main/10.2/

Teaching a man to fish is worse than giving him a fish! !

1. Query Cursor SearchCursor

  SearchCursorfunction to establish a read-only cursor on a feature class or table. SearchCursor can be used to iterate over row objects and extract field values. Searches can be restricted using where clauses or fields, and the results sorted.

insert image description here

  The first parameter in front is a required parameter, that is, the layer file to be queried; {fields} is generally used, that is, the field to be queried. If not filled, all fields are included by default.

1. Example 1

The attribute table is shown in the figure:
insert image description here

Through the query cursor, query ['Id', 'BSM', 'WYBS']three fields:

import arcpy

# 设置工作空间
arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

# 设置操作的图层文件
shapeFile = '测试shap1.shp'

# 设置要查询的字段名
fieldName = ['Id', 'BSM', 'WYBS']

# 获取游标对象并且迭代
with arcpy.da.SearchCursor(shapeFile, fieldName) as cursor:
    for row in cursor:
        print row[0], row[1], row[2]

result:

1 1 wybs_0
2 2 wybs_1
3 3 wybs_2
4 4 wybs_3
5 5 wybs_4

2. Example 2

The attribute table is shown in the figure:
insert image description here

The query code is as follows:

import arcpy

# 设置工作空间
arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

# 设置操作的图层文件
shapeFile = '测试shap1.shp'

cursor = arcpy.SearchCursor(shapeFile)
for row in cursor:
    print row.getValue('Id'), row.getValue('BSM'), row.getValue('WYBS')

The result is as follows:

1 1 wybs_0
2 2 wybs_1
3 3 wybs_2
4 4 wybs_3
5 5 wybs_4

3. Example 3 (used together with the where parameter)

  We can add a where_clauseparameter and use it together. The value of this parameter is a string, which is equivalent to the wherequery condition followed by the sql query statement.

The attribute table is shown in the figure:
insert image description here

The query code is as shown in the figure:

import arcpy

# 设置工作空间
arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

# 设置操作的图层文件
shapeFile = '测试shap1.shp'

sql_exe = "\"WYBS\" = 'wybs_2'"
fieldName = ['Id', 'BSM', 'WYBS']
with arcpy.da.SearchCursor(shapeFile, fieldName, where_clause=sql_exe) as cursor:
    for row in cursor:
        print row[0], row[1], row[2]

result:

3 3 wybs_2

As you can see, we only found WYBS = wybs_2the records of .

Two, update the cursor UpdateCursor

  UpdateCursorThe function creates a cursor that updates or deletes rows in the specified feature class, shapefile, and table. This cursor holds data locks until the script completes or the update cursor object is dropped.

  UpdateCursor can be used to read and write data, that is: both query and update! Updates contain overwrites and deletes! !

insert image description here

  The first parameter in front is a required parameter, that is, the layer file to be updated; {fields} is generally used, that is, the field to be updated. If not filled, all fields are included by default.

1. Query Example 1

  Used toUpdateCursor query data and SearchCursorsimilar, I will only demonstrate one kind here, and the other ones can be SearchCursorwritten by yourself. code show as below:

import arcpy

# 覆盖更新一
def coverSearchOne(shapeFile):
    # 要更新的字段(建议用元组,这样就不能更改了,也不能重复)
    fieldNameList = ('Id', 'BSM', 'WYBS')

    with arcpy.da.UpdateCursor(shapeFile, fieldNameList) as cursor:
        for row in cursor:
            print row[0], row[1], row[2]



if __name__ == '__main__':
    # 设置工作空间
    arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

    # 设置操作的图层文件
    shapeFile = '测试shap1.shp'

    coverSearchOne(shapeFile=shapeFile)

The result is as follows:

1 1 wybs_0
2 2 wybs_1
3 3 wybs_2
4 4 wybs_3
5 5 wybs_4

2. Update Example 1

Raw data:
insert image description here

Update code:

def coverUpdateOne(shapeFile):
    # 要更新的字段(建议用元组,这样就不能更改了,也不能重复)
    fieldNameList = ('Id', 'BSM', 'WYBS')

    with arcpy.da.UpdateCursor(shapeFile, fieldNameList) as cursor:
        for row in cursor:
            if row[2] == 'wybs_2':
                row[2] = 'wybs100'
            # 更新这一行
            cursor.updateRow(row)

if __name__ == '__main__':
    # 设置工作空间
    arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

    # 设置操作的图层文件
    shapeFile = '测试shap1.shp'

    coverUpdateOne(shapeFile=shapeFile)

Updated data:
insert image description here

3. Update Example 2

Raw data:
insert image description here

Update code:

def coverUpdateTwo(shapeFile):
    # 要更新的字段(建议用元组,这样就不能更改了,也不能重复)
    fieldNameList = ('Id', 'BSM', 'WYBS')

    # 获取更新游标
    cursor = arcpy.UpdateCursor(shapeFile, fieldNameList)

    # 遍历每一行
    for row in cursor:
        if row.getValue('WYBS') == 'wybs100':
            row.setValue('WYBS', 'wybs_1000')
        cursor.updateRow(row)

if __name__ == '__main__':
    # 设置工作空间
    arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

    # 设置操作的图层文件
    shapeFile = '测试shap1.shp'

    coverUpdateTwo(shapeFile=shapeFile)

Updated data:
insert image description here

4. Update Example 3 (combined with where)

  At this point, I believe everyone understands that updating is actually querying the data, then judging whether the data meets the updating conditions, and finally updating. The update combined with where is actually the same as the where query, so I won't demonstrate it here.

5. Delete a row Example 1

Raw data:
insert image description here

Delete code:

def coverDeleteOne(shapeFile):
    # 要更新的字段(建议用元组,这样就不能更改了,也不能重复)
    fieldNameList = ('Id', 'BSM', 'WYBS')

    with arcpy.da.UpdateCursor(shapeFile, fieldNameList) as cursor:
        for row in cursor:
            if row[2] == 'wybs_1000':
                # 删除一行数据,注意deleteRow不加任何参数
                cursor.deleteRow()

if __name__ == '__main__':
    # 设置工作空间
    arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

    # 设置操作的图层文件
    shapeFile = '测试shap1.shp'

    coverDeleteOne(shapeFile=shapeFile)

Deleted data:
insert image description here

6. Delete example 2

Raw data:
insert image description here

Delete code:

def coverDeleteTwo(shapeFile):
    # 要更新的字段(建议用元组,这样就不能更改了,也不能重复)
    fieldNameList = ('Id', 'BSM', 'WYBS')

    # 获取更新游标
    cursor = arcpy.UpdateCursor(shapeFile, fieldNameList)

    # 遍历每一行
    for row in cursor:
        if row.getValue('WYBS') == 'wybs_0':
            # 删除一行,这种方式需要加参数
            cursor.deleteRow(row)

if __name__ == '__main__':
    # 设置工作空间
    arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

    # 设置操作的图层文件
    shapeFile = '测试shap1.shp'

    coverDeleteTwo(shapeFile=shapeFile)

7. Delete example 3 (used together with the where parameter)

According to the gourd painting, write according to the above.

3. Insert the cursor InsertCursor

  Insert rows into a feature class, shapefile, or table. InsertCursor returns an enumeration of distributed row objects. A new row object can be obtained from the enumeration object of the inserted row using the newRow method. Each call to insertRow on the cursor creates a new row in the table with the initial value set to the value in the input row.

insert image description here

  The first parameter in front is a required parameter, that is, the layer file to be updated.

1. Insert example 1

Raw data:
insert image description here

Insert code:

def coverInsertOne(shapeFile):
    # 要插入的字段
    fieldNameList = ('Id', 'BSM', 'WYBS')

    with arcpy.da.InsertCursor(shapeFile, fieldNameList) as cursor:
        for i in range(1, 10):
            # 插入一行
            cursor.insertRow((i, i, 'wybs_' + str(i)))
        # 删除游标对象和 row 对象解除对数据的锁定
        del cursor

if __name__ == '__main__':
    # 设置工作空间
    arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

    # 设置操作的图层文件
    shapeFile = '测试shap1.shp'

    coverInsertOne(shapeFile=shapeFile)

Inserted data:
insert image description here

4. Insert example 2

Raw data:
insert image description here

Insert code:

def coverInsertTwo(shapeFile):
    # 要插入的字段
    fieldNameList = ('Id', 'BSM', 'WYBS')

    cursor = arcpy.InsertCursor(shapeFile, fieldNameList)

    for i in range(10):
        row = cursor.newRow()
        row.setValue('Id', i)
        row.setValue('BSM', i)
        row.setValue('WYBS', 'wybs_' + str(i))
        cursor.insertRow(row)
    # 删除游标对象和 row 对象解除对数据的锁定
    del cursor

if __name__ == '__main__':
    # 设置工作空间
    arcpy.env.workspace = r"E:\arcpy_study\Arcpy编程开发(从小白到大神)\测试文件"

    # 设置操作的图层文件
    shapeFile = '测试shap1.shp'

    coverInsertTwo(shapeFile=shapeFile)

Inserted data:
insert image description here

Summarize

These contents are used in the documentation, I just sorted them out, teaching people how to fish is worse than giving them a fish! !

Guess you like

Origin blog.csdn.net/qq_47188967/article/details/131432977