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 Answers 2
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.
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– Salman2019年07月17日 14:09:55 +00:00Commented Jul 17, 2019 at 14:09
out_table
?