Hi,
First of all you should really use syntax highlighting: Posting Code blocks in the new GeoNet
To recursively loop through folder and sub folder and detect the layerfiles (.lyr) you can use the arcpy.da.Walk functionality (asuming you have a recent version of ArcGIS).
import arcpy
import os
workspace = r"D:\Xander\GeoNet"
walk = arcpy.da.Walk(workspace, datatype="Layer")
for dirpath, dirnames, filenames in walk:
for filename in filenames:
print (os.path.join(dirpath, filename))
This prints each .lyr file it finds:
D:\Xander\GeoNet\StackedLabels\aLayer.lyr
D:\Xander\GeoNet\StackedLabels\subfolder\subsubfolder\subsubsubfolder\AnotherLayer.lyr
In case you want to add all the layer found to an existing MXD you should open the MXD before the loop and add put the add layerfile logic inside the loop. Adding a lot of layer to an MXD will probably make it very slow.
Your code might look like this (in case you run this inside a session of ArcMap and want to add the layers to the current session of ArcMap, hence the keyword "CURRENT"):
import arcpy
import os
# suppose you want to add it to the current MXD (open MXD)
mxd = arcpy.mapping.MapDocument("CURRENT")
dataFrame = arcpy.mapping.ListDataFrames(mxd, "*")[0]
# base folder
workspace = r"D:\Xander\GeoNet"
walk = arcpy.da.Walk(workspace, datatype="Layer")
for dirpath, dirnames, filenames in walk:
for filename in filenames:
layerfile = os.path.join(dirpath, filename)
addlayer = arcpy.mapping.Layer(layerfile)
arcpy.mapping.AddLayer(dataFrame, addlayer, "BOTTOM")
arcpy.RefreshTOC()
arcpy.RefreshActiveView()
del addlayer, mxd
In case you want to run it as a standalone script and/or add the layers to a different existing MXD, you should replace the keyword "CURRENT" on line 5 by a reference (string containing path and filename) to the MXD.