AnsweredAssumed Answered

Update cursor not replacing values in python script

Question asked by jbrengel on May 25, 2017
Latest reply on May 27, 2017 by jbrengel

Hello, I am trying to use an update cursor on an attribute table of a feature class (called Lancowatersheds) in order to replace certain characters in values in a specific field of the table (called STORMWATER).  I tried the following code and when I used the print function to show desired changes (remove all "-" and "\" from all values in the STORMWATER field and replace with " "), the update cursor did not seem to work (values still had those funky characters in them):

 

# Import arcpy
import arcpy

# Set environments
from arcpy import env
env.workspace = "C:/GIS_Data/Test"
arcpy.env.overwriteOutput = True

# Input feature class
in_fc = "C:/GIS_Data/Test/TEST/Lancowatersheds.shp"

with arcpy.da.UpdateCursor(in_fc, ["STORMWATER"]) as cursor:
    for row in cursor:
        row[0].replace("-", " ")
        row[0].replace("\\", " ")
        cursor.updateRow(row)
        print row
    del row
    del cursor

 

Here's a list of all the original values in the STORMWATER field:

 

 ['SUSQUEHANNA RIVER', 'PEQUEA CREEK', 'OCTORARO CREEK', 'MILL CREEK', 'LITTLE CONESTOGA CREEK', 'CONOWINGO CREEK', 'CONEWAGO CREEK-DAUPHIN', 'CONESTOGA RIVER', 'COCALICO CREEK', 'CHICKIES CREEK', 'DONEGAL\LOWER CHICKIES CREEK']

 

I then put all the desired values from the "STORMWATER" field into a list (e.g. there should be no weird characters in the values because I ran the update cursor).  I wanted to use this list to select certain features from the original shapefile "Lancowatersheds" and make that selection a standalone feature class.  Here's that code:

 

wsheds = ['SUSQUEHANNA RIVER', 'PEQUEA CREEK', 'OCTORARO CREEK', 'MILL CREEK', 'LITTLE CONESTOGA CREEK', 
        'CONOWINGO CREEK', 'CONEWAGO CREEK DAUPHIN', 'CONESTOGA RIVER', 'COCALICO CREEK', 'CHICKIES CREEK', 'DONEGAL LOWER CHICKIES CREEK']

for shed in wsheds:
    arcpy.MakeFeatureLayer_management(in_fc, "lyr")
    whereExp = "\"STORMWATER\" = \'{0}\'".format(shed)
    arcpy.SelectLayerByAttribute_management("lyr", "NEW_SELECTION", whereExp)
    arcpy.CopyFeatures_management("lyr", '{0:s}'.format(shed))

  

I got the above code to work for all the objects in the my "wsheds" list whose original values did not contain a "-" or "\" , but for the two objects in the STORMWATER field whose original values contained those characters, no such luck.  Maybe automating is a bit much for such a small data set, but I guess my ultimate goal is to understand how to use update cursors to replace any character in a value in any field of an attribute table.  I could see this being a useful skill when dealing with much larger data sets. Thanks!!

Outcomes