Can someone help me understand what the last 2 lines of this code does:
import arcpy
arcpy.env.workspace = "c:/esripress/python/data/exercise07"
arcpy.env.overwriteOutput = True
copy = arcpy.CopyFeatures_management("airports.shp","Results/airports.shp")
fc = "Results/airports.shp"
cursor = arcpy.da.UpdateCursor(fc, ["STATE"], ' "STATE" <> \'AK\'')
for row in cursor:
row[0] = "AK"
cursor.updateRow(row)
del row
del cursor
I understand that the loop function goes through each record that does not have a value of 'AK' and gives that record a value of "AK". But what I don't understand is what the del row
and del cursor
are meant to do.
1 Answer 1
Those are relics of an earlier style of arcpy
cursors. del row, cursor
were previously used to clean-up after the script was run by deleting the row
and cursor
objects. Now, the proper usage is to wrap the cursor in a with
statement, which both opens and closes the row and cursor objects, as follows:
import arcpy
arcpy.env.workspace = "c:/esripress/python/data/exercise07"
arcpy.env.overwriteOutput = True
copy = arcpy.CopyFeatures_management("airports.shp","Results/airports.shp")
fc = "Results/airports.shp"
with arcpy.da.UpdateCursor(fc, ["STATE"], ' "STATE" <> \'AK\'') as cursor:
for row in cursor:
row[0] = "AK"
cursor.updateRow(row)
-
1Your answer is not entirely correct. You can still (and need to, in some cases) use the old method of creating the server object and deleting it when done. For example for insert operations, it is easier to do it that way sometimes (pro.arcgis.com/en/pro-app/arcpy/data-access/…). The main advantage of the with statement is that it automatically removes the lock on the data if the operation fails, which the other method does not do. Create cursor - error - it skips the del part and your data are locked.najel– najel2017年09月01日 13:19:40 +00:00Commented Sep 1, 2017 at 13:19
-
1@PhilippNagel when would you need to use the old method of creating cursors?Squanchy– Squanchy2018年09月22日 18:51:25 +00:00Commented Sep 22, 2018 at 18:51
-
1Now that I think about it, I'm not sure what I was thinking of back then.najel– najel2018年09月22日 21:25:34 +00:00Commented Sep 22, 2018 at 21:25
-
From UpdateCursor page "Update cursors also support with statements to reset iteration and aid in removal of locks. However, using a del statement to delete the object or wrapping the cursor in a function to have the cursor object go out of scope should be considered to guard against all locking cases." My understanding of that, in other words: To make entirely sure there is something not hanging, you still better use "del row, cursor". Or you can wrap it into function so with end of function all in local scope gets automatically deleted.Miro– Miro2019年03月28日 00:18:36 +00:00Commented Mar 28, 2019 at 0:18
State
value of any airport that was not previously in Alaska