3

I'm creating a table and then trying to delete that table inside the same for loop as follows:

for fc in fcList:
    arcpy.GenerateNearTable_analysis(inFile, fc, out_table)
    arcpy.JoinField_management(inFile, "Obj_ID", out_table, "In_FID", ["NEAR_DIST"])
    arcpy.Delete_management(out_table)

But for some reason the delete statement isn't working. The table still exists after the script completes 'successfully'. When I just run the delete statement alone afterwards (means outside the for loop), then the table is deleted. But I need to delete it inside the for loop so that I can loop further. I have to put some more statements within the for loop later and the table needs to be deleted first for the upcoming statements to work.

Does the Delete_management statement not work within a for loop for any reason?

  • 2
    How did you define out_table? – umbe1987 Jul 17 at 13:07
  • 1
    Can you also please describe the "upcoming statements" you need to execute after the table is deleted? – umbe1987 Jul 17 at 13:08
  • out_table is just a simple table that Generate Near Table tool creates. Please see my comment below for the upcoming statements. – Salman Jul 17 at 14:10
4

I suspect some sort of file lock is occurring. An alternative approach you could try is to set overwrite to True before the loop

arcpy.env.overwriteOutput = True

This means your out_table is constantly overwritten and then you use the Delete outside the loop as you have.

2

As discussed in this accepted answer:

I think this is an issue with ArcGIS having open file handles on the files in your temp folder (out_table).

The accepted solution suggested to wrap all the process you need to do in a function, call that and, as the function is returned (finish its execution), all variables within its scope is cleared.

Only then you can call the Delete_management function.

Try something like this and see if it works:

def your_func_name(fc):
    arcpy.GenerateNearTable_analysis(inFile, fc, out_table)
    arcpy.JoinField_management(inFile, "Obj_ID", out_table, "In_FID", ["NEAR_DIST"])

for fc in fcList:
    your_func_name(fc)
    arcpy.Delete_management(out_table)
  • This is useful but as I said I need to add some more tools in that function which would create the same out_table again. So those tools wont work if the table already exists. That is why I wanted to delete that table each time after Generate Near Table tool ran, within the function. – Salman Jul 17 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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