I want to clean this code in such a way that there are not so many for loops. For loops in the following code are placed to trap FCs in multiple group layers and do some work on them. My Data in TOC looks like this
Data (Main Group Layer)
--->Sub Group (First Sub Group)
----->FCs (in First Sub Group)
--->Sub Group 2 (Second Sub Group)
----->FCs (in Second Sub Group)
............
Although the code works fine Just wondering if we can make it more sleek.
Can you update it if there is room for improvement?
import arcpy
import fileinput
proj = arcpy.mp.ArcGISProject('CURRENT')
#m = proj.listMaps()[0]
m = proj.activeMap
ml = m.listLayers("Data") # First Group Layer
for gl in ml:
if gl.isGroupLayer: # Check if its Group Layer
arcpy.AddMessage("-"+gl.name+"-")
mml = gl.listLayers()
for sgl in mml:
if sgl.isGroupLayer: # Check if its Sub Group Layer
arcpy.AddMessage("--"+sgl.name+"--")
lyrs = sgl.listLayers()
for lyr in lyrs:
arcpy.AddMessage(lyr.name)
with arcpy.da.SearchCursor(lyr,['Assetic_ID','FL_ID']) as cur:
for rows in cur:
with open("C:\\test\\file.csv", 'a') as f:
f.write('{0},{1}\n'.format(rows[0],rows[1]))
#print (rows, file =f)
arcpy.AddMessage("Finished")
ListLayers
once, because it already returns all layers, including nested ones.