Remove group layer with arcpy

5151
2
Jump to solution
04-14-2015 03:29 AM
Yaron_YosefCohen
Occasional Contributor II

Hi,

i try to remove a group layer with arcpy for several mxd's with this code:

import arcpy,os,sys
import arcpy.mapping
from arcpy import env

env.workspace = r"D:\PROJECTS\atar_ashpa_depo\gis"
for mxdname in arcpy.ListFiles("*.mxd"):
    print mxdname # print list of mxd's in the folder
    mxd = arcpy.mapping.MapDocument(r"D:\PROJECTS\atar_ashpa_depo\gis\\" + mxdname)
    dfList = arcpy.mapping.ListDataFrames(mxd, "*")
    for df in dfList:
        for lyr in arcpy.mapping.ListLayers(mxd, "", df):
            if lyr.GroupLayer.name == "segment-BL.dwg Group Layer":
                arcpy.mapping.RemoveLayer(df, lyr)
                print 'RemoveLayer 3'  
    mxd.save()
del mxd

but get en error:

land use map

Traceback (most recent call last):
  File "C:\yaron\shonot\software\gis\tools\YARON_SCRIPTS\RemoveLayer by name with 2 df option 1.py", line 35, in <module>
    if lyr.GroupLayer.name == "segment-BL.dwg Group Layer":
AttributeError: 'Layer' object has no attribute 'GroupLayer'
>>> 

thanks for any help

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
FrédéricPRALLY
Esri Contributor

Hi,

First check if your layer is a group layer and after check if this name match with your search name.

See code below:

import arcpy,os,sys
import arcpy.mapping
from arcpy import env

env.workspace = r"D:\PROJECTS\atar_ashpa_depo\gis"
for mxdname in arcpy.ListFiles("*.mxd"):
    print mxdname # print list of mxd's in the folder
    mxd = arcpy.mapping.MapDocument(r"D:\PROJECTS\atar_ashpa_depo\gis\\" + mxdname)
    dfList = arcpy.mapping.ListDataFrames(mxd, "*")
    for df in dfList:
        for lyr in arcpy.mapping.ListLayers(mxd, "", df):
            if lyr.isGroupLayer:
                if lyr.name == "segment-BL.dwg Group Layer":
                    arcpy.mapping.RemoveLayer(df, lyr)
                    print 'RemoveLayer 3'
    mxd.save()
del mxd

Have fun,

Fred

View solution in original post

0 Kudos
2 Replies
FrédéricPRALLY
Esri Contributor

Hi,

First check if your layer is a group layer and after check if this name match with your search name.

See code below:

import arcpy,os,sys
import arcpy.mapping
from arcpy import env

env.workspace = r"D:\PROJECTS\atar_ashpa_depo\gis"
for mxdname in arcpy.ListFiles("*.mxd"):
    print mxdname # print list of mxd's in the folder
    mxd = arcpy.mapping.MapDocument(r"D:\PROJECTS\atar_ashpa_depo\gis\\" + mxdname)
    dfList = arcpy.mapping.ListDataFrames(mxd, "*")
    for df in dfList:
        for lyr in arcpy.mapping.ListLayers(mxd, "", df):
            if lyr.isGroupLayer:
                if lyr.name == "segment-BL.dwg Group Layer":
                    arcpy.mapping.RemoveLayer(df, lyr)
                    print 'RemoveLayer 3'
    mxd.save()
del mxd

Have fun,

Fred

0 Kudos
Yaron_YosefCohen
Occasional Contributor II

thanks Fred !!!

0 Kudos