Wednesday, 11 July 2018

arcpy - Add multiple Layer files in subdirectories to mxd using python



I have more than 300 layer files located in many sub-Folders and sub-sub-Folders. All Sub Folders are located in one large directory.I read Use python to add layers to TOC and I try, with arcpy, to detect all the layers and add them to mxd. Is it possible?



Answer



If you work with ArcGIS 10.1 SP1 or above, you can use the arcpy.da.Walk() function:


import arcpy, os

workspace = r"C:\directory"
mxd = arcpy.mapping.MapDocument(r"C:\Map.mxd")

df = arcpy.mapping.ListDataFrames(mxd, "*")[0]

walk = arcpy.da.Walk(workspace, datatype="Layer")

for dirpath, dirnames, filenames in walk:
for filename in filenames:
arcpy.mapping.AddLayer(df, arcpy.mapping.Layer(os.path.join(dirpath, filename)))

mxd.save()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...