1

I am using below code to remove any layer if it has zero features in it.

mxd = arcpy.mapping.MapDocument("CURRENT")
aDF = mxd.activeDataFrame
namE = ["No_Work_Done"]
if int(arcpy.GetCount_management(namE[0])[0]) < 1:
    try:
        arcpy.mapping.RemoveLayer(aDF, namE[0])
    except Exception as d:
        print(d.message)
    else:
        print("No Work Done or Conflict Present in Data\n")

However this is returning run-time error and assertion error as below

Runtime error 
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\utils.py", line 182, in fn_
    return fn(*args, **kw)
  File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\mapping.py", line 1845, in RemoveLayer
    assert isinstance(remove_layer, Layer)
AssertionError

What could be the problem here?

1 Answer 1

4

namE[0] is a string. RemoveLayer method expects a Layer instance. You need to get Layerinstance of layer "No_Work_Done". You should use arcpy.mapping.ListLayers method. This method gives you list of layers as a list of Layer instances, not as a list of strings. When you change the script as follows, the layer will be removed.

mxd = arcpy.mapping.MapDocument("CURRENT")
aDF = mxd.activeDataFrame
namE = ["No_Work_Done"]
if int(arcpy.GetCount_management(namE[0])[0]) < 1:
    try:
        # ADD/CHANGE FOLLOWING TWO LINES
        REMOVE = arcpy.mapping.ListLayers(aDF, namE[0])[0]
        arcpy.mapping.RemoveLayer(aDF, REMOVE)
    except Exception as d:
        print(d.message)
    else:
        print("No Work Done or Conflict Present in Data\n")

You may be wondering why you don't get error when using GetCount_management with namE[0]. Because that method accepts a layer as a string, but RemoveLayer doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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