ArcMap – How to Delete Layer Using Python

arcmaparcpylayers

Problem:

  • I'm trying to loop through all my layers looking for layer named "CADAnnotation".
  • If the layer exists then remove the layer from the mxd

Notes:

  • Running from Stand-Alone script (ie. NOT within Arcmap)
  • "CADAnnotation" Data Type is a CAD Annotation Feature Class
  • "CADAnnotation" is NOT in a geodatabase, it's created from a AutoCAD .dwg
  • "CADAnnotation" is within a Group Layer named "ACAD"
  • If the group layer "ACAD" can be deleted that also removes "CADAnnotation" that would be great.

Code thus far:

for item in mxds:
    print (item)
    mxd = arcpy.mapping.MapDocument(item)
    df=arcpy.mapping.ListDataFrames(mxd,"Project Area")[0]
    for lyr in arcpy.mapping.ListLayers(mxd, "*",df):
        if lyr.name == "CADAnnotation":
            print(lyr.dataSource)
            arcpy.Delete_management("CADAnnotation")
            print("Layer Deleted")
        else:
            pass

Notes on Code:

  • I can find the layer no problem
  • the line arcpy.Delete_management("CADAnnotation") does not work throws an error.

Question:

  • How to I remove "CADAnnotation" and/or "ACAD" group layer?

Best Answer

Do you want to actually delete the layer from the geodatabase or remove it from the mxd?

If you just want to remove the layer from your mxd, replace arcpy.Delete_management("CADAnnotation") with arcpy.mapping.RemoveLayer(df, lyr)

If you want to delete the data source you can do this.

for item in mxds:
   print (item)
   mxd = arcpy.mapping.MapDocument(item)
   df=arcpy.mapping.ListDataFrames(mxd,"Project Area")[0]
   for lyr in arcpy.mapping.ListLayers(mxd, "*",df):
      if lyr.name == "CADAnnotation":
         arcpy.mapping.RemoveLayer(df, lyr)
         print(lyr.dataSource)
         arcpy.Delete_management(lyr.dataSource)
         print("Layer Deleted")
      else:
         pass
Related Question