Problem using Arcpy Update Cursor

686
5
12-28-2011 01:03 PM
BillyArmstrong
New Contributor
Hi all,
I'm trying to loop through all the rows of a shapefile field and update the row values, and can't get the Arcpy Update Cursor to work properly. My script crashes when I try to pass the new value that I want to update the row object with. I've tried passing the value as an integer and a string (the field I'm trying to update is an integer type), and I've tried using the row.setValue method as well. Below is my code for creating and using the cursor (code would be properly indented in PyScriptor). If anyone can tell me what I'm doing wrong I would really appreciate it.

rows = arcpy.UpdateCursor(outshp,"","",fname,"")
for row in rows:

         isyear = 1
         row.fname = isyear
         rows.updateRow(row)

del row
del rows

thanks in advance!

Billy
Tags (2)
0 Kudos
5 Replies
JakeSkinner
Esri Esteemed Contributor
Hi Billy,

You will just need to wrap the field name in quotations within the UpdateCursor function.  Ex:

rows = arcpy.UpdateCursor(outshp,"", "", "fname", "")
for row in rows:
    isyear = 1
    row.fname = isyear
    rows.updateRow(row)

del row
del rows


Also, you can preserve the indentation of your code by using the code tags (# symbol).
0 Kudos
BillyArmstrong
New Contributor
Hi Jake,
The field name is actually a variable from previous geoprocessing operations, and was used to name a newly created field. If I manually enter the specific field in quotes the Update Cursor works fine. I'm trying to pass the variable so it can loop through a series of shapefiles which get updated with a unique field names. The Update Cursor seems to accept the variable name, however the row.<name> method crashes every time with it.

thanks,

Billy
0 Kudos
JakeSkinner
Esri Esteemed Contributor
I don't believe you will be able to pass a variable for a Update/Search/Insert Cursor.  When you specify 'row.fname', the cursor looks for a field called 'fname', even if 'fname' was defined as a variable before hand.  The cursor cannot distinguish this.  I would recommend using the Field Calculator.  You can pass a variable with this function.  Ex:

outshp = "Test.shp"

fname = "id"
isyear = 1

arcpy.CalculateField_management(outshp, fname, isyear)
0 Kudos
RobertJones6
New Contributor
Another way you could try it would be like the following, since your code succeeds with manual field naming versus derived:

rows = arcpy.UpdateCursor(outshp,"","",      ---> "%s" %(fname,) <-----    ,"")
0 Kudos
BillyArmstrong
New Contributor
Thanks for the replies. I ended up using the Field Calculator and it worked great.

Billy
0 Kudos