游标类型
类型 | 方法 | 说明 |
搜索游标 | arcpy.da.SearchCursor | 检索行 |
更新游标 | arcpy.da.UpdateCursor | 更新和删除行 |
插入游标 | arcpy.da.InsertCursor | 插入行 |
使用
搜索游标
遍历所有
结果展示
代码
import arcpy
shppath =r"C:\Users\admin\Desktop\excelfile\1.shp"
with arcpy.da.SearchCursor(shppath, ["SHAPE@XY","class"]) as cursor:for row in cursor:print(row[0], row[1])
import arcpy
shppath =r"C:\Users\admin\Desktop\excelfile\1.shp"
cursor = arcpy.da.SearchCursor(shppath, ["SHAPE@XY","class"])
for row in cursor:print(row[0], row[1])
del cursor
添加条件遍历
结果展示
代码
import arcpy
shppath =r"C:\Users\admin\Desktop\excelfile\1.shp"
with arcpy.da.SearchCursor(shppath, ["SHAPE@XY","class"], """"class" = 0""") as cursor:for row in cursor:print(row[0], row[1])
游标回到初始位置(重新遍历)
结果展示
代码
import arcpy
shppath =r"C:\Users\admin\Desktop\excelfile\1.shp"
with arcpy.da.SearchCursor(shppath, ["SHAPE@XY","class"]) as cursor:for row in cursor:if row[1]==1:cursor.reset()print(row[0], row[1])
访问对象标识符字段
结果展示
代码
import arcpy
shppath =r"C:\Users\admin\Desktop\excelfile\1.shp"
with arcpy.da.SearchCursor(shppath, ["SHAPE@XY","OID@"]) as cursor:for row in cursor:print(row[0], row[1])
更新游标
更新
结果展示
代码(class在原始的基础上增加1)
import arcpy
shppath =r"C:\Users\admin\Desktop\excelfile\1.shp"
with arcpy.da.UpdateCursor(shppath, ["SHAPE@XY","class"]) as cursor:for row in cursor:row[1]=row[1]+1cursor.updateRow(row)
with arcpy.da.SearchCursor(shppath, ["SHAPE@XY","class"]) as cursor:for row in cursor:print(row[0], row[1])
删除
结果展示
代码(删除class为3的行)
import arcpy
shppath =r"C:\Users\admin\Desktop\excelfile\1.shp"
with arcpy.da.UpdateCursor(shppath, ["SHAPE@XY","class"]) as cursor:for row in cursor:if row[1] == 3:cursor.deleteRow()
with arcpy.da.SearchCursor(shppath, ["SHAPE@XY","class"]) as cursor:for row in cursor:print(row[0], row[1])
插入游标
结果展示
代码
import arcpy
shppath =r"C:\Users\admin\Desktop\excelfile\1.shp"
with arcpy.da.InsertCursor(shppath, ["SHAPE@XY","class"]) as cursor:cursor.insertRow([(-119.158325598, 34.03489167),2])
with arcpy.da.SearchCursor(shppath, ["SHAPE@XY","class"]) as cursor:for row in cursor:print(row[0], row[1])