ArcPy – How to Iterate Fields and Remove Null Values and Spaces

arcpynull

Is it possible to iterate fields in a table to remove Null values and spaces (where there is no value)? In other words, I would like to replace Null and " " with "" (no space).

Cobbling arcpy scripts, I have this:

import arcpy

fc = "{path to geodatabase and feature class}"
fieldList = arcpy.ListFields(fc)
for field in fieldList:
    with arcpy.da.UpdateCursor(fc, [fieldList]) as cursor:
        for row in cursor:
            if row[0] == None:
                row[0] = ''
            elif row[0] == ' ':
                row[0] = ''
                cursor.updateRow(row)

print "Processing complete"

I'm aware of using "remove" in the field calculator, but you have to go field by field. I'd like to do this for the whole table.

Best Answer

I think you've got it the wrong way around. Not for field in fieldList then for row in cursor, rather for row in cursor and for field in fieldList except you will need to index properly... you're only trying to adjust the first field in the fieldList with row[0].

import arcpy

fc = "{path to geodatabase and feature class}"
fieldList = arcpy.ListFields(fc)
# remove some key fields from the list
desc = arcpy.Describe(fc)

fieldList.remove(desc.shapeFieldName)
fieldList.remove(desc.OIDFieldName)

with arcpy.da.UpdateCursor(fc, [fieldList]) as cursor:
    fRange = range(len(fieldList)) # create an index 0 to the number of elements in fieldList - 1

    for row in cursor:
        SomethingUpdated = False # a flag for changes

        # step through each field in the row by its index
        for index in fRange:
            if row[index] == None:
                row[index] = ''         #set the field to empty string
                SomethingUpdated = True #flag to store row
            else:
                val = str(row[index]).replace(" ","") # remove spaces
                if len(val) == 0:
                    # value is nothing but spaces or empty
                    row[index] = ''         #set the field to empty string
                    SomethingUpdated = True #flag to store row

        if SomethingUpdated:
            cursor.updateRow(row)

print "Processing complete"

Be aware that no checking is being done for field types; trying to set '' into a numeric field will cause this script to crash hard!