Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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
share|improve this question

2 Answers 2

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"
share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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