Original User: rfairhur24I have other scripts that I would like to modify. The scripts work when the Feature Class is the top Layer within the TOC. Can you provide an example of a recursive layer search? Thanks. Previously I used
for lyr in arcpy.mapping.ListLayers(lyr):.
See this post for a way to do it one group layer deep.import arcpy
inMXD = r'c:\test.mxd'
outMXD = r'c:\test1.mxd'
rLayer = 'test3' #Name of reference layer
mLayer = 'test4' #Name of layer to be replaced and moved
lyrFile = arcpy.mapping.Layer(r'c:\Test4.lyr') #Layer file used to replace layer
mxd = arcpy.mapping.MapDocument(inMXD)
for df in arcpy.mapping.ListDataFrames(mxd): #loop data frames
for lyr in arcpy.mapping.ListLayers(mxd,"",df): #loop layers
if lyr.isGroupLayer == 1: #Is layer a group layer
for glyr in arcpy.mapping.ListLayers(lyr): #loop layer in group layer
if glyr != lyr: #Not Group Layer Name
if glyr.name.lower() == mLayer: #Layer to be worked on
Recursion involves setting up a second method that can call itself when it encounters each group layer, so it does not matter how deep the groups go. Basically it would be something like this function (untested) which is called for every layer until you find the layer you want or you have no more layers:def layerInGroup(lyr, layerName):
if lyr.isGroupLayer == 1:
for glyr in arcpy.mapping.ListLayers(lyr): #loop layer in group layer
if glyr != lyr: #Not Group Layer Name
resultlyr = layerInGroup(glyr, layerName) # Recursively call the function for group in a group
if resultlyr != None:
return resultlyr # We found the layer deeper inside the group so return it and stop function
elif lyr.name.lower() == layerName: # Not a group layer so test to see it is the one we want.
return lyr # This is the layer we want so return it and stop function.
return None # All tests failed to find layer we want so return None