I have spent a couple days digging through forums here, ESRI help and elsewhere and each variation of the codes I have tried has not worked. As best as I can tell this is due to my attempt to loop through multiple fields or something to do with formatting when the fields parameter is collected using the field as text option.
#Simple search and replace script
import arcpy
#define where clause to format for correct database type
def buildWhereClause(table, field, value):
"""Constructs a SQL WHERE clause to select rows having the specified value
within a given field and table."""
# Add DBMS-specific field delimiters
fieldDelimited = arcpy.AddFieldDelimiters(table, field)
# Determine field type
fieldType = arcpy.ListFields(table, field)[0].type
# Add single-quotes for string field values
if str(fieldType) == 'String':
value = "'%s'" % value
# Format WHERE clause
whereClause = "%s = %s" % (fieldDelimited, value)
return whereClause
# Retrieve input parameters: the feature class, the search term, the replace
# term, and the fields affected by the search and replace.
fc = arcpy.GetParameterAsText(0)
oldValue = arcpy.GetParameterAsText(1)
newValue = arcpy.GetParameterAsText(2)
fields = arcpy.GetParameterAsText(3)
# Create the SQL expression for the update cursor. Here this is
# done on a separate line for readability.
whereClause = buildWhereClause(fc, fields, oldValue)
# Create the update cursor
rows = arcpy.da.UpdateCursor(fc, fields, whereClause)
# Perform the update and move to the next row as long as there are
# rows left
for row in rows:
row[0] = newValue
rows.updateRow(row)
# Delete the cursors to remove any data locks
del row, rows
What I need it to do is obtain all the fields in which the user wants to replace the oldValue with the newValue by reading in the multiple fields the user has checked the box for. Then loop through each field and in any instance where oldValue occurs re-write it to = newValue until all the fields have been updated.
Added:
Here is the traceback info thrown when this is run as a tool inside Model Builder
Traceback (most recent call last):
File "C:\arcgisserver\ETL_Scripts\Scripts\RewriteValues.py", line 44, in <module>
whereClause = buildWhereClause(fc, fields, oldValue)
File "C:\arcgisserver\ETL_Scripts\Scripts\RewriteValues.py", line 25, in buildWhereClause
fieldType = arcpy.ListFields(table, field)[0].type
IndexError: list index out of range