Select to view content in your preferred language

adding 3 lyr layer in all mxd in one folder

286
1
07-18-2022 12:22 PM
Paul-EmmanuelLeroux
Emerging Contributor

hello I have been helped to create a script to add 3 .lyr layers in many mxd in one folder containing several subfolder with .mxd

The following script is not working,

How I am supposed to run it, python on arcmap 10.8 or python consol on window 10?

Many thanks for any input .

Paulo

 

import arcpy
import arcpy.mapping as m
import os

root_folder = r"path\to\root\folder"

add_lyr_1 = r"path\to\file1.lyr"
add_lyr_2 = r"path\to\file2.lyr"
add_lyr_3 = r"path\to\file3.lyr"

## create list of lyr files
add_lyrs = [add_lyr_1, add_lyr_2, add_lyr_3]

mxd_paths = []

## add all mxd paths to a list
for root, dirs, files in os.walk (root_folder):
    for f in files:
        if f.endswith(".mxd"):
            mxd_paths.append("{0}\\{1}".format(root, f))

## print to test
#print(mxd_paths)

for mxd_doc in mxd_paths:
    mxd_name = mxd_doc.rsplit("\\")[-1]
    arcpy.AddMessage(mxd_name)

    ## access the mxd
    mxd = m.MapDocument(mxd_doc)

    ## only access the desired dataframe
    ## you might want to use a dataframe name / wildcard to
    ## add layers to correct dataframe if you have multiple
    df = m.ListDataFrames(mxd)[0]

    ## add each layer file, one on top of the other.
    for lyr_file in add_lyrs:
        add_lyr = m.Layer(lyr_file)
        m.AddLayer(df, add_lyr ,"TOP")

    mxd.save()

 

0 Kudos
1 Reply
DonMorrison1
Frequent Contributor

Can you provide more detail on how it is failing - for instance the error messages?

0 Kudos