Wednesday, May 18, 2011

Search Cursors

I couldn't say it better, so from the ArcGIS Help:
"The SearchCursor function establishes a read-only cursor on a feature class or table. The SearchCursor can be used to iterate through row objects and extract field values. The search can optionally be limited by a where clause or by field, and optionally sorted."

Looking Object Model of SearchCursor() we see the following:

Let do a example:

import arcpy
fc = arcpy.GetParameter(0)
rows = arcpy.SearchCursor(fc)
for row in rows:
   print 'hello rows!'
del rows

This is a very simple example where the end user would provide a feature class as an input and the output would be displayed for each row in the rows object.

Not only is it import to understand cursors, but it's also important to understand what a cursor object will give you. It's a collection of Row objects. Row Objects have collection of methods that include getValue(), setValue(), inNull(), and setNull(). The names pretty much explain what each function does, but here is a graphic to explain it better:
If you use the web help like I often do to look up examples, how-to, etc.. for geoprocessing with python, you'll notice that many times the examples show a field value from a row being returned as such:

value = row.FieldName

Though there is nothing wrong with this, I do not prefer this method. I prefer calling the row method getValue().

value = row.getValue("FieldName")

Also remember, you cannot set values with a SearchCursor(), if you need to alter or add rows/features use the Update or Insert cursor objects.