Friday, May 27, 2011

Using the Update Cursors

The UpdateCursor() is a cursor object that allows for the update or deletion of rows in a feature class or table.  The cursor will place a lock on the data that will persist until the object is deleted or when the script terminates.

To create an UpdateCursor object, you must provide a data set on creation. As shown in the brief example below

ds = r"c:\temp\feat.shp"
uCursor = arcpy.UpdateCursor(ds)
# Do something with object


Here is a complete list of the optional and required parameters for UpdateCursor:
When you are done updating a row, call the updateRow() to commit your action that was performed on the row.

ds = r"c:\temp\feat.shp"
updateField = "Foo"
updateValue = "bar"
uCursor = arcpy.UpdateCursor(ds)
for row in uCursor:
   row.setValue(updateField,updateValue)
   row.updateRow(row)
del row, uCursor

In the above example, a feature class called feat.shp is having the field 'Foo' updated with the value 'bar'. Notice that the del function is called after the actions are performed. This should be done at the end of all cursor operation in order to drop the schema lock that is held on the data. If you do not, no other operations will be allowed on your data, and most likely the script will fail.

The deleteRow() on the UpdateCursor allows for the deletion of the current row of a table or feature class and is pretty straight forward to use:

ds = r"c:\temp\feat.shp"
uCursor = arcpy.UpdateCursor(ds)
for row in uCursor:
   uCursor.deleteRow(row)
del row, uCursor

This script example deletes all the rows in the data set.

Enjoy