How to iterate fields and remove Null values and spaces

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!


I shall offer my variation:

import arcpy

fc = "{path to geodatabase and feature class}"

fieldList = [f.name for f in arcpy.ListFields(fc) if f.type == "String"]

if fieldList:

    with arcpy.da.UpdateCursor(fc, [fieldList]) as cursor:
        for row in cursor:
            for i in range (len(fieldList)):
                if not row[i]:
                    row[i] == ""
                elif row[i] == " ":
                    row[i] == ""
            cursor.updateRow(row)

print "Processing complete"

I'm not sure that I understand what you are asking, because your question does not describe what is not working in your code, but I think:

    for row in cursor:
        if row[0] == None:
            row[0] = ''
        elif row[0] == ' ':
            row[0] = ''
            cursor.updateRow(row)

needs to be:

    for row in cursor:
        if row[0] == None:
            row[0] = ''
        elif row[0] == ' ':
            row[0] = ''
        cursor.updateRow(row)

You will also need to filter out text fields from your other fields because they are the only ones you can write strings to.

Tags:

Null

Arcpy