Saturday, 27 April 2019

Using arcpy.da.InsertCursor to insert entire row that is fetched from search cursor?


This is a simple process using the legacy cursors, but I cannot figure out how to do it with the newer Insert Cursor from the Data Access module. I basically want to take the entire row from a Search Cursor created on an SDE feature class in one database, and insert that row into an SDE feature class in another database using the Insert Cursor. The code below is how I am doing this using the legacy cursors, and it works quite well, but I would like to take advantage of the faster performance of the Data Access cursors. This runs on a list of feature classes that all have different numbers of fields (and different geometry types), though the schema for each feature class is identical between the databases (the databases are basically copies of one another):


    sourceAddRows = arcpy.SearchCursor(sourceFC)
targetAddRows = arcpy.InsertCursor(targetFC)
for sourceAddRow in sourceAddRows:
targetAddRows.insertRow(sourceAddRow)

Answer



As long as your source and target FC's have the same number of fields and have the same geometry type, this should work:


# Get field objects from source FC
#

dsc = arcpy.Describe(sourceFC)
fields = dsc.fields

# List all field names except the OID field
#
fieldnames = [field.name for field in fields if field.name != dsc.OIDFieldName]

# Create cursors and insert new rows
#
with arcpy.da.SearchCursor(sourceFC,fieldnames) as sCur:

with arcpy.da.InsertCursor(targetFC,fieldnames) as iCur:
for row in sCur:
iCur.insertRow(row)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...