ArcPy 游标 setValues

-1 投票
2 回答
4350 浏览
提问于 2025-04-17 21:21

我正在尝试遍历一些字段,检查这些字段是否为空或者是空白的,如果是的话就用999999来填充。这个脚本运行得很好,但似乎没有执行到if条件,因为它什么都没有打印出来,也没有改变任何字段的值。

fc = "C:\Users\\bbrock\Documents\ArcGIS\Ports.shp"

# Create a search cursor 
#
rows = arcpy.SearchCursor(fc) 

# Create a list of string fields
fields = arcpy.ListFields(fc, "", "String")

for row in rows:
    for field in fields:
        if field.type != "Geometry":
            if row.getValue(field.name) == '':
                row.setValue(field.name, 'ondciqwn')                
                print "%s: Value = %s" % (field.name, row.getValue(field.name))

            if row.isNull(field.name):
                row.setValue(field.name, 'bvadvfe')             
                print "%s: Value = %s" % (field.name, row.getValue(field.name))     

2 个回答

0

添加这个内容是因为有人建议在ArcGIS 10.1中使用 with arcpy.da.updateCursor as... 这样可以更好地处理错误,并且速度更快。我经过大幅度的修改后,成功让它运行起来,因为它有不同的属性、签名等等。具体如下:

fc = "C:/Users/bbrock/Documents/ArcGIS/Default.gdb/Ports_Admin_Join"

fields = arcpy.ListFields(fc, "", "String")

for field in fields:
    with arcpy.da.UpdateCursor(fc, field.name) as rows:
        for row in rows:
            if field.type != "geometry" and field.length > 5:
                if row[0] == None or row[0] == ' ':
                    row[0] = '999999'
                    rows.updateRow(row)    
                    print "%s: Value = %s" % (field.name, row[0])
0

SearchCursor函数用来创建一个只读的游标,也就是说,你只能查看数据,而不能修改它。如果你想要更新或者删除数据,可以使用UpdateCursor。你的代码大概是这样的:

import arcpy
rows = arcpy.UpdateCursor(fc) 
fields = arcpy.ListFields(fc, "", "String")
for row in rows:
    for field in fields:
        if field.type != "Geometry":
            if row.getValue(field.name) == '':
                row.setValue(field.name, 'ondciqwn')                
                print "%s: Value = %s" % (field.name, row.getValue(field.name))

            if row.isNull(field.name):
                row.setValue(field.name, 'bvadvfe')             
                print "%s: Value = %s" % (field.name, row.getValue(field.name)) 
    rows.updateRow(row)

撰写回答