I would like to automate the importation of a directory as a hierarchy of group layers in the Table Of Content of ArcMap with Arcpy. I already saw and adapt these posts and scripts :
- Importing file geodatabase (GDB) to table of contents (TOC) of ArcMap?
- Adding group layer, renaming it from folder name, then adding layers to it from that folder, using ArcPy/Python?
Unfortunatelly, each code had only one level depth, so there’s no group layer(s) into another group layer. In other words, there’s only one group layer per directory and the hierarchy of the directory isn’t preserve. The expected result is shown in the images below.
Here's my code:
import arcpy
import os
folder =r'C:' #root folder
template_group_layer = r'C:' #empty layer
mxd=arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
groups={}
for path, dirs, files in arcpy.da.Walk(folder): #search in directory and create group layer
for d in dirs:
lyr=arcpy.mapping.Layer(template_group_layer) #add empty group layer to ArcMap
lyr.name=d
arcpy.mapping.AddLayer(df,lyr)
groups[d]=arcpy.mapping.ListLayers(mxd,d,df)[0]
for f in files: #select files that are shapefiles and insert them in their groups as the directory architecture
fp=os.path.join(path,f)
dsc=arcpy.Describe(fp)
print dsc
lyr=None
view=None
if dsc.dataType == 'ShapeFile':
lyr=arcpy.management.MakeFeatureLayer(fp,os.path.basename(fp))[0] #edit 1 - remove layer in dataframe to prevent duplicate
arcpy.mapping.RemoveLayer(df, lyr)
print lyr
else:continue
if path==folder and lyr:
lyr.visible=False
arcpy.mapping.AddLayer(df,lyr)
else:
d=os.path.basename(path)
arcpy.mapping.AddLayerToGroup(df, groups[d], lyr, "BOTTOM")
Current result