Tuesday, July 10, 2012

Insert Cursor (arcpy.da) at 10.1

The insert cursor, just like the old insert cursor object, is used to write a new row to an existing table.  When using the InserCursor object you must tell the cursor object what type of geometry you will be using.  So if your feature class is a point feature class, use "SHAPE@XY" but if it's a polygon or polyline, use "SHAPE@".  It should be noted that "SHAPE@" is valid for point features as well.

The InsertCursor has one function called insertRow(), which is a list object with field values in it.

Table Examples:

from arcpy import da
with da.InsertCursor(fc, ["name"]) as cursor:
   cursor.insertRow(["BOB SMITH"])

Feature Class Example (Point):

from arcpy import da
with da.InsertCursor(fc, ["name", "SHAPE@"]) as cursor:
   cursor.insertRow(["A Point",(-77, 34)])



Feature Class Example (Line):

from arcpy import da

array = arcpy.Array([arcpy.Point(-77, 34),
                     arcpy.Point(-77.1, 34.1),
                     arcpy.Point(-77.2, 34.2)])
polyline = arcpy.Polyline(array)

with da.InsertCursor(fc, ["name", "SHAPE@"]) as cursor:
   cursor.insertRow(["A Line", polyline])
Feature Class Example (Polygon):

from arcpy import da

array = arcpy.Array([arcpy.Point(-77, 34),
                     arcpy.Point(-77, 34.1),
                     arcpy.Point(-77.2, 34.1),
                     arcpy.Point(-77, 34)])
pg = arcpy.Polygon(array)

with da.InsertCursor(fc, ["name", "SHAPE@"]) as cursor:
   cursor.insertRow(["Polygon", pg])

Enjoy