0

I'm using the code below in order to attempt to clone a row in a feature class and add that same row to the same feature class after updating its metadata (Name, date_start, date_end, etc.)

The problem is that it is duplicating the rows several times, when expecting 2 rows i get 4, expecting 3, getting 8.

inFeatureClass  = "C:\TS.gdb\IN_TSGIS"
arcpy.MakeFeatureLayer_management(inFeatureClass, temp_layer_name)
insert_feature_table(temp_layer_name, temp_layer_name, query_single_col('UID',UID), update_fields)

def query_single_col(col, value):
    return '"'+str(col)+'" = ' + str(value)

def insert_feature_table(inputfeatureclass, insertfeatureclass, expr, fields):
     with arcpy.da.InsertCursor(insertfeatureclass, ("*")) as i_cursor:
        with arcpy.da.SearchCursor(inputfeatureclass, ("*"), where_clause=expr) as s_cursor:
            for s_row in s_cursor:
                i_cursor.insertRow(s_row)
                break

Any ideas as to why that is?

3
  • Are you interested in overwriting the row values, or adding new rows with the updated values?
    – Aaron
    Commented Aug 1, 2014 at 16:03
  • 3
    I'm not sure why you wouldn't just use the UpdateCursor instead?
    – ianbroad
    Commented Aug 1, 2014 at 16:06
  • @Aaron I'm interested in adding new rows with the updated values.
    – Sebastian
    Commented Aug 1, 2014 at 17:42

1 Answer 1

3

It can't possibly be a good idea to use an insert cursor on a feature class while you're in the middle of a search cursor on the same one. I think your search cursor is coming across the rows that had been inserted earlier in the loop, and inserting them again, perhaps several times.

My suggestion is to run the search cursor, save the rows to memory, then write them to the table once the search cursor has completed.

inFeatureClass = r"C:\TS.gdb\IN_TSGIS"
arcpy.MakeFeatureLayer_management(inFeatureClass, temp_layer_name)
insert_feature_table(temp_layer_name, temp_layer_name, query_single_col('UID',UID), update_fields)

def query_single_col(col, value):
    return '"'+str(col)+'" = ' + str(value)

def insert_feature_table(inputfeatureclass, insertfeatureclass, expr, fields):
    records = []
    with arcpy.da.SearchCursor(inputfeatureclass, ("*"), where_clause=expr) as s_cursor:
        for s_row in s_cursor:
            # Make any changes to the row values you want here
            # e.g. s_row[3] = "some new value"
            records.append(s_row)
    with arcpy.da.InsertCursor(insertfeatureclass, ("*")) as i_cursor:
        for r in records:
            i_cursor.insertRow(r)
    return None

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.