arcpy.mapping.RemoveLayer question

375
2
Jump to solution
03-01-2019 07:32 AM
ChrisHolmes
Occasional Contributor III

Hello all,

I have a function that looks like:

def RemoveLayers(mxd,layers):
    arcpy.AddMessage('RemoveLayers-mxd: ' + mxd)
    arcpy.AddMessage('RemoveLayers-layers: ' + layers)
    mxd = arcpy.mapping.MapDocument(mxd)
    df=arcpy.mapping.ListDataFrames(mxd,"Layers")[0]
    for lyr in arcpy.mapping.ListLayers(mxd):
        if lyr.name.upper() in (layers):
            arcpy.mapping.RemoveLayer(df, lyr)
            arcpy.AddMessage('Layer {} has been removed.'.format(lyr))
                
    mxd.save()
    del mxd‍‍‍‍‍‍‍‍‍‍‍‍
‍‍‍‍‍‍‍‍‍‍‍‍

The line being used to call the function is:

RemoveLayers(ProposedMxd,"'OP_SITE_MNT','LU_BOUNDARY_MNT - OUTLINE','LU_BOUNDARY_MNT - WHITE FILLED','COMM_BOUNDARY_MNT'")

What I see as output is:

Any ideas as to why these 2 layers in red are also being removed, what am I missing?

Thanks!

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

It is removing SITE_MNT because the string exists in your long string with all the layer names.  What you need to do is create a list from your list of layer names.

>>> s = "'OP_SITE_MNT','LU_BOUNDARY_MNT - OUTLINE','LU_BOUNDARY_MNT - WHITE FILLED','COMM_BOUNDARY_MNT'"
>>> print('SITE_MNT' in s)
True
>>>
>>> l = s.split(",")
>>> l
["'OP_SITE_MNT'", "'LU_BOUNDARY_MNT - OUTLINE'", "'LU_BOUNDARY_MNT - WHITE FILLED'", "'COMM_BOUNDARY_MNT'"]
>>> 
>>> print("'SITE_MNT'" in l)
False
>>> print("'OP_SITE_MNT'" in l)
True

Since you use nested quoted strings, you will need to be careful with your in comparison with the list. 

View solution in original post

0 Kudos
2 Replies
JoshuaBixby
MVP Esteemed Contributor

It is removing SITE_MNT because the string exists in your long string with all the layer names.  What you need to do is create a list from your list of layer names.

>>> s = "'OP_SITE_MNT','LU_BOUNDARY_MNT - OUTLINE','LU_BOUNDARY_MNT - WHITE FILLED','COMM_BOUNDARY_MNT'"
>>> print('SITE_MNT' in s)
True
>>>
>>> l = s.split(",")
>>> l
["'OP_SITE_MNT'", "'LU_BOUNDARY_MNT - OUTLINE'", "'LU_BOUNDARY_MNT - WHITE FILLED'", "'COMM_BOUNDARY_MNT'"]
>>> 
>>> print("'SITE_MNT'" in l)
False
>>> print("'OP_SITE_MNT'" in l)
True

Since you use nested quoted strings, you will need to be careful with your in comparison with the list. 

0 Kudos
ChrisHolmes
Occasional Contributor III

Awesome, thanks for the quick reply Joshua. List it is!

0 Kudos