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")
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.

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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.