Update Cursor: deleting the cursor

322
4
10-24-2011 11:21 AM
FrankLahm_III
New Contributor
Hi,
It appears that although I am using del cursor, my cursors are not really deleting, and are still locking the geodatabase.

#while loop
        intable = FC
        rows = arcpy.UpdateCursor(intable)
        row = rows.next()
        while row:
            date = str(row.getValue("BEGINDATE"))
            dateStr = str(date)
            print dateStr
            dateRep = dateStr.replace("-", "")
            print dateRep
            dateNew = dateRep[:8]
            print dateNew
            row.setValue("BEGINDATE_Temp", dateNew)
            rows.updateRow(row)
            row = rows.next()
        del row, rows

This is a temporary field, so after it is used for a calculation I try to delete the field
       try:
            arcpy.DeleteField_management(FC, ["BEGINDATE_Temp"])
        except:
            arcpy.AddMessage("Could not delete BEGINDATE_Temp field from " + FC)

I am continually getting the "Could not delete...." message.

When testing this in the python window in catalog, it appears that the cursors are not really being deleted by "del row, rows".  They are still locking the geodatabase and preventing me from deleting the fields.  Any idea what I am doing wrong or how one can truly remove cursor objects?

Thanks,
-f
Tags (2)
0 Kudos
4 Replies
MathewCoyle
Frequent Contributor
I found the easiest way to handle this is to call functions anytime you use a cursor. Simple example.
def main():
    rows = arcpy.UpdateCursor(layer)
    for row in rows:
        row.Field = "value"
        rows.updateRow(row)
    del rows
if __name__ == '__main__':
    main()

This should completely clear the cursors when the function is complete.
0 Kudos
RDHarles
Occasional Contributor
Hi Mathew,
Can you explain what the purpose is of this line in your code example?
I tried to look it up but I'm not clear on the use.
Thanks!

if __name__ == '__main__':
0 Kudos
RaphaelR
Occasional Contributor II
0 Kudos
MathewCoyle
Frequent Contributor
It basically restricts execution if it is imported to another script to specific functions called, unless the script itself is executed. Rafael's link gives a good explanation.
0 Kudos