Tuesday, May 31, 2011

Using the Insert Cursor

This is my 4th article discussing the cursor objects in the ArcPy module.  In previous posts, I have talked about both search and update cursors in depth, so if you want to learn more about those, please feel free to search my earlier postings.

An InsertCursor inserts rows into a feature class or table.  The InsertCursor like the other cursor types returns an enumerable object that returns a row object.  New row objects can be created using a newRow() on the enumeration object (the cursor object).  After a row is created using the newRow(), use the insertRow() to save the newly created row into the existing table or feature class.

To create an InsertCursor, you just need to pass in a data set.  There is an optional parameter of spatial reference, which would be the spatial reference of the input data set, and a Cursor object is returned.
Here is a complete description:

Example of InsertCursor and a table

import arcpy
table = r"c:\temp\table.shp"
iCursor = arcpy.InsertCursor(table)
row = iCursor.newRow()
del iCursor
del row

In the example about, a single new row is created, and the field "foo" is filled with the value "bar" then inserted in the existing table.

Example of InsertCursor and a feature class

import arcpy

fc = r"C:\TEMP\pts.shp"
# Use the Describe() to get the Shape Field name
desc = arcpy.Describe(fc)
# Create the cursor
iCursor = arcpy.InsertCursor(fc)
# Create a new row
row = iCursor.newRow()
# Create new location
pt = arcpy.Point(-75,35)
# set the input values
row.setValue(desc.shapeFieldName, pt)
# insert the row
# delete the cursor references to release
# schema locks
del iCursor
del row

No comments: