Select to view content in your preferred language

Delete_management sometimes won't delete rasters?

943
5
07-03-2018 09:49 AM
AlexEpp
Emerging Contributor

If I run this code:

import arcpy
import os


def main():
    in_gdb = 'test_arc_interface.gdb'
    in_features = os.path.join(in_gdb, 'section_grid')
    in_raster = os.path.join(in_gdb, 'bitumen')

    arcpy.ResetEnvironments()
    arcpy.CheckOutExtension('Spatial')
    arcpy.env.workspace = in_gdb

    f_raster = arcpy.PolygonToRaster_conversion(in_features, 'OBJECTID', 'in_memory/f_raster', 'MAXIMUM_AREA')
    table = arcpy.sa.ZonalStatisticsAsTable(f_raster, 'Value', in_raster, 'in_memory/r_table')
    print(arcpy.Delete_management(table))
    print(arcpy.Delete_management(f_raster))
    print(arcpy.Exists(table))
    print(arcpy.Exists(f_raster))

    arcpy.env.workspace = 'in_memory'
    print(arcpy.ListRasters())
    print(arcpy.ListFeatureClasses())


if __name__ == '__main__':
    main()

I get:

true
true
False
True
['f_raster']
[]

i.e. Delete_management(f_raster) returns true, Exists(f_raster) returns false, but arcpy still lists it in ListRasters(). What is going on?

0 Kudos
5 Replies
DanPatterson_Retired
MVP Emeritus

I suspect that it is held on to and treated as intermediate data until such time as the script is finished

http://pro.arcgis.com/en/pro-app/tool-reference/appendices/using-the-in-memory-output-workspace.htm

which might account for its presence.  Perhaps try saving the in-memory version to disk and see if delete works then

0 Kudos
AlexEpp
Emerging Contributor

Thanks for the quick reply!

I'm not entirely sure how I would 'save the in-memory version to disk' (I'm new to ArcGIS, sorry), but I can run something like this:

f_raster_disk = arcpy.Raster(f_raster)
f_raster_disk.save(os.path.join(in_gdb, 'f_raster'))

and then Exists(f_raster_disk) works as expected (Exists(f_raster) still returns True, though).

0 Kudos
JoeBorgione
MVP Emeritus

I have found that arcpy.Exists isn't reliable.  os.path.exisits is.  But, arcpy.Delete_management won't error out if you provide a feature class or raster that does not exist.

That should just about do it....
0 Kudos
AlexEpp
Emerging Contributor

I don't think my problem is that Exists is unreliable, though. I think the raster somehow still exists after I delete it, because, for example, if I call Delete_management on it a second time, I get "arcgisscripting.ExecuteError: ERROR 000601: Cannot delete in_memory\f_raster.  May be locked by another application."

0 Kudos
DanPatterson_Retired
MVP Emeritus

Could have been worse...

http://pro.arcgis.com/en/pro-app/tool-reference/tool-errors-and-warnings/001001-010000/tool-errors-a...

basically in-memory is a bit of a misnomer for most operations.  If you can run timing functions on your scripts you will generally see that.

0 Kudos