Remove all layers except one

275
2
Jump to solution
05-04-2020 06:58 AM
DamianMilne
New Contributor II

Hi, I'm making the transition from ArcMap to ArcGIS Pro so please forgive my ignorance...

At the start of my Arcpy script, I am trying to delete all of my layers in my layout except 'Coast'. When I run my script below it crashes ArcGIS Pro. Any advice graciously accepted.

aprx = arcpy.mp.ArcGISProject("CURRENT")
mp = aprx.listMaps("Map")[0]

# Remove all layers except coast
keeplyr = mp.listLayers("Coast")
for rmlyr in mp.listLayers():
if rmlyr != keeplyr:
mp.removeLayer(rmlyr)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
1 Solution

Accepted Solutions
DavidPike
MVP Regular Contributor

it seems like you're trying to find an equality between two layer objects, i'd probably utilise the .name property for evaluation. you've also got a bad indent at the bottom. Might work, might not, I'm not a doctor.

aprx = arcpy.mp.ArcGISProject("CURRENT")
mp = aprx.listMaps("Map")[0]

# Remove all layers except coast

for rmlyr in mp.listLayers():
if rmlyr.name != "Coast":
mp.removeLayer(rmlyr)

View solution in original post

2 Replies
DavidPike
MVP Regular Contributor

it seems like you're trying to find an equality between two layer objects, i'd probably utilise the .name property for evaluation. you've also got a bad indent at the bottom. Might work, might not, I'm not a doctor.

aprx = arcpy.mp.ArcGISProject("CURRENT")
mp = aprx.listMaps("Map")[0]

# Remove all layers except coast

for rmlyr in mp.listLayers():
if rmlyr.name != "Coast":
mp.removeLayer(rmlyr)

View solution in original post

DamianMilne
New Contributor II

Thank you David, turns out the layers I was trying to remove were actually group layers (apologies for omitting that fairly significant detail), however your response did put me on the right track. For the benefit of other newbs like me here is my code snippit.

for rmlyr in mp.listLayers():
if rmlyr.isGroupLayer:
mp.removeLayer(rmlyr)‍‍‍
0 Kudos