Pergunta

I'm trying to iterate through fields, check if a field is null or blank and fill with 999999. The script runs fine, but doesn't seem to be executing the if expression because it doesn't print anything and doesn't change the values of any of the fields.

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))     
Foi útil?

Solução

The SearchCursor function establishes a read-only cursor. Instead, you can use an UpdateCursor to update or delete rows. Your code would be something like:

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)

Outras dicas

Adding this because it was recommended to use with arcpy.da.updateCursor as... for better exception handling and speed for ArcGIS 10.1, and I was able to get that to function with significant reworking as it has different attributes, signature, etc. As follows:

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])
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top