1

I am new to python.

Will someone help me with the code to import the same layer into all the arcmap files in a folder on my desktop?

I used the code below to import the layer into one map but I need to import it into 20 maps.

import arcpy.mapping as mapping
mxd = mapping.MapDocument("CURRENT")
df = mapping.ListDataFrames(mxd)[0]
layer= mapping.Layer(r"c: PATH TO LAYER FILE")
mapping.AddLayer(df, layer, "TOP")
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Aug 23, 2019 at 13:02

2 Answers 2

1

One thing to note here is that mapping.MapDocument("CURRENT") works only within ArcMap and refers to the current open MXD. With this in mind, is necessary that you pass the path to your MXD file as the parameter of mapping.MapDocument(). Because you want to refer to multiple MXD files, you'll need to get the paths of all the MXD files and then iterate through them, doing your process for each one of them. Assuming you had all your MXD files in one folder, you can easily create a list of all the MXD files using glob (no need to install it as it makes part of Python's standard library). Here is a snippet that should accomplish what you are looking after:

import glob
import arcpy.mapping as mapping
mxd_paths = glob.glob(r'C:\path to mxds\*.mxd')
layer = mapping.Layer(r"c: PATH TO LAYER FILE") # no need to define the layer each loop if it is the same for every MXD
for mxd_path in mxd_paths:
 mxd = mapping.MapDocument(mxd_path)
 df = mapping.ListDataFrames(mxd)[0]
 mapping.AddLayer(df, layer, "TOP")
 mxd.save() # this is very important; otherwise you won't be able to see the changes

You can run this script outside or within ArcMap and it will add the layer to your 20 MXD files.

answered Aug 23, 2019 at 17:26
0

My Arcmap 10.7.1 does not recognize .GLOB but I found another solution. Thank you everybody for your help.

import arcpy, os
import arcpy.mapping as mapping
layer = mapping.Layer(r"C:\PATH_TO_LAYER FILE")
for root, dirs, files in os.walk(r"c:\Users\jcook\Desktop\Batch"):#I have folder named Batch on desktop
 for f in files:
 if f.endswith(".mxd"):
 mxd = root + '\\' + f
 mxd_doc = mapping.MapDocument(mxd)
 df = mapping.ListDataFrames(mxd_doc)[0]
 mapping.AddLayer(df, layer, "TOP") 
 mxd_doc.save()
Marcelo Villa
6,0982 gold badges20 silver badges39 bronze badges
answered Aug 23, 2019 at 23:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.