2

This question already has an answer here:

I have a function outputTblContents which contains

def outputTblContents ( path ):
    rows = arcpy.SearchCursor(path, fields="alpha; beta")
    for row in rows:
        print("{0} => {1}").format(row.getValue("alpha"), row.getValue("beta"))

The function that called outputTblContents then tries to delete the folder that path is in, but is unable to because it’s still in use by the script. I guess arcpy.SearchCursor spawns it’s own thread. How do I wait for it to be finished so I can safely delete the shapefiles and clean up?

outputTblContents(pathToShpfile)
shutil.rmtree(pathToTempDir)

Here is the error WindowsError: [Error 32] The process cannot access the file because it is being used by another process: '\\\\storage1\\gis\\dev\\temp\\ collated_a1.shp….sr.lock'

marked as duplicate by Brad Nesom, Michael Stimson, PolyGeo Jun 29 '15 at 21:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

You're script above probably still has a lock onto the data. Specifically this line:

rows = arcpy.SearchCursor(path, fields="alpha; beta")

You've got two ways to get around the lock.

Delete the rows variable after your loop

rows = arcpy.SearchCursor(path, fields="alpha; beta")
for row in rows:
    print("{0} => {1}").format(row.getValue("alpha"), row.getValue("beta"))
del rows

Or you can call the search cursor within a with block. Doing this will let python release the object when the with block completes. In your case, when the for row in rows completes

with arcpy.SearchCursor(path, fields="alpha; beta") as rows:
    for row in rows:
        print("{0} => {1}").format(row.getValue("alpha"), row.getValue("beta"))

Edit: Here is the arcpy.da.SearchCursor example

with arcpy.da.SearchCursor(path,["alpha","beta"]) as rows:
    for row in rows:
        print("{} => {}".format(row[0],row[1]))
  • Also, check out the arcpy.da search cursors. ESRI considers the non-da ones to be legacy from 10.1 onwards. Heres a link for more information: resources.arcgis.com/en/help/main/10.1/index.html#//… – Cody Jun 29 '15 at 17:09
  • with the with statement I'm getting AttributeError: __exit__ – Celeritas Jun 29 '15 at 17:15
  • I added an example for the arcpy.da one. see if that works – Cody Jun 29 '15 at 17:18
  • 1
    What version of Arc are you running? arcpy.da is not available before 10.1; might be the same for the with statement. – recurvata Jun 29 '15 at 17:22
  • 1
    @Cody, arcpy.SearchCursor does not support with, only arcpy.da.SearchCursor supports the use of with, see gis.stackexchange.com/questions/148828/… (paragraph after first code block) – Michael Stimson Jun 29 '15 at 22:14

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