Hello community,
I am trying to add the 3 same .lyr layers into different mxd in a folder with serveral sub-folders and many sub-sub folders.
I was helped to draw a script. However, I failed to run it. I would really apprciate if the community could help me to correct the script PLEASE!
I have another question where is this specific script supposed to be run, in Python for Arcmap or Python console on Windows?
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()
Paulo
I originally wrote this in StackExchange 🙂
How have you tried to run it so far? What errors are you getting? Details and screenshots will help.
As a personal preference I use PyScripter to run Python Scripts outside of the ArcMap/Pro environment.
You can also use IDLE that is installed with Python, or you can create/load a script within the ArcMap/Pro software.
In IDLE the error appear after the last part:
>>> for lyr_file in add_lyrs:
add_lyr = m.Layer(lyr_file)
m.AddLayer(df, add_lyr ,"TOP")
Traceback (most recent call last):
File "<pyshell#11>", line 2, in <module>
add_lyr = m.Layer(lyr_file)
File "C:\Program Files (x86)\ArcGIS\Desktop10.8\ArcPy\arcpy\arcobjects\mixins.py", line 429, in __init__
super(LayerMixin, self).__init__(lyrfile)
File "C:\Program Files (x86)\ArcGIS\Desktop10.8\ArcPy\arcpy\arcobjects\_base.py", line 47, in __init__
for arg in args))
ValueError: Objet\xa0: source of data not valid in the layer CreateObject
Can you show the full code you are running? It could be a path error to the lyr files you are attempting to use.
What have you added for the paths here?
add_lyr_1 = r"path\to\file1.lyr"
add_lyr_2 = r"path\to\file2.lyr"
add_lyr_3 = r"path\to\file3.lyr"
Sorted
I corrected something in the first loop:
for root, dirs, files in os.walk(root_folder):
for f in files:
if f[-4:]==(".mxd"):
in the second loop I have a problem with mxd = m.MapDocument(mxd_doc)