1

I am trying to use RemoveLayer within the mapping module, but seem to be getting mixed results. I do the following to add a layer to the map

mxd = arcpy.mapping.MapDocument("CURRENT") # define map document
lyr = arcpy.mapping.Layer(r"C:\test.lyr") # define layer object
df = arcpy.mapping.ListDataFrames(mxd) # list data frames
arcpy.mapping.AddLayer(df[0],lyr) #  add layer 

Now that the layer is added, I am trying to use arcpy.mapping.RemoveLayer to remove the layer from the map. I do the following.

arcpy.mapping.RemoveLayer(df[0],lyr)

But this doesn't work. The layers still exist in the map. But if I try the following code where I list the layers and then loop through and use RemoveLayer, it works now. Why?

lyrlist = arcpy.mapping.ListLayers(mxd)
for i in lyrlist:
    arcpy.mapping.RemoveLayer(df[0],i)

Is this because Layer objects don't work with RemoveLayer for some reason?

1
  • 1
    you will probably need to get your layer from the data frame (ListLayers) and not just create a new one.. even though the datasource and name of the layer is the same a newly created layer is different to an existing layer. Commented Feb 7, 2019 at 23:13

1 Answer 1

2

You're still referencing the layer file with your variable lyr. You'll need to find it in your mxd before you can remove it.

Maybe something like this:

lyrlist = arcpy.mapping.ListLayers(mxd)
lyr = [l for l in lyrlist if l.name == "test"] [0]
arcpy.mapping.RemoveLayer(df[0],lyr)

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.