4

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
5

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"
0

I think I've answered my own question....here it is...

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



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

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.