[GIS] Add a .lyr file to multiple mxd’s within a specified folder using python

arcgis-10.0arcpypython

I need to create a python script that will look in a certain folder or workspace, and add a certain .lyr file to each mxd in the folder. I am able create a python script that adds the layer by specifying the path to each .mxd, but ideally, I don't want the name of each .mxd to have to be hard coded in the script. I've tried using the arcpy.ListFiles("*.mxd") but I can't get my script to read the list when I need to specify the mxd's to point to when identifying the dataframe in the arcpy.mapping.ListDataFrames function.
This is what I have so far…Not sure what I'm missing.

import arcpy
import arcpy.mapping
import os
import sys
from arcpy import env

env.workspace = workspace = "M:\projects\mcag\Project_Site_Packet"
mxdlist = arcpy.ListFiles ("*.mxd")
for mxd in mxdlist:
    mapdoc = arcpy.mapping.MapDocument(mxd)
    df = arcpy.mapping.ListDataFrames(mapdoc, "Layers")
    addlayer = arcpy.mapping.Layer(r"M:\projects\mcag\Project_Site_Packet\Subject Property.lyr")
    arcpy.mapping.AddLayer(df,addlayer,"TOP")
    mapdoc.save()
    del mapdoc, addlayer

Best Answer

Instead of this line of code:

env.workspace = workspace = "M:\projects\mcag\Project_Site_Packet"

I would use any one of the following:

env.workspace = r"M:\projects\mcag\Project_Site_Packet"
env.workspace = "M:\\projects\\mcag\\Project_Site_Packet"
env.workspace = "M:/projects/mcag/Project_Site_Packet"
Related Question