1

I have this one specific layer in a bunch of mxd files with a broken data source. I am working on a script to automate fixing the data source. I am having trouble getting it to loop through a folder and fix the layer on all mxd files in that same folder.

This is the script I have so far:

#Import modules
import arcpy
from arcpy import env

#Put file path for the folder containing mxds, where I have my sample file path
env.workspace = r"G:\Geomatics\Map Requests\2017-07-24_TrailClosures"

#Looping through all mxd documents, list layers and replace those layers MRGTrails layer with proper data source
for file in arcpy.ListFiles("*.mxd"):
    mxd = arcpy.mapping.MapDocument(file)
    df = arcpy.mapping.ListDataFrames("*.mxd", "Layers")[0]
    for lyr in arcpy.mapping.ListLayers(mxd, "*", df):
      if lyr.name == "Trails":
        lyr.replaceDataSource(r'G:\Geomatics\Data\Regional\MRG.gdb', "FILEGDB_WORKSPACE", "Trails_Sentiers", validate=False)

    mxd.save()

closed as too broad by PolyGeo Jun 20 '18 at 22:02

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    What error are you getting? What is the specific question that you have? – Tom Jun 20 '18 at 21:22
2

You had a few minor typos. Honestly, this question will probably get closed for being unique to your particular set of mistakes. But here's a solution, with comments describing changes from the original:

import arcpy
from arcpy import env

env.workspace = r"G:\Geomatics\Map Requests\2017-07-24_TrailClosures"

for file in arcpy.ListFiles("*.mxd"):
    mxd = arcpy.mapping.MapDocument(file) # Changed 'files' to file
    # Iterate over all data frames, because what if one has a different name...or if a map has multiple data frames
    # And pass the mxd object to the function--not the mxd wildcard
    for df in arcpy.mapping.ListDataFrames(mxd):
        for lyr in arcpy.mapping.ListLayers(mxd, "*", df):
            if lyr.name == "Trails":
                lyr.replaceDataSource(r'G:\Geomatics\Data\Regional\MRG.gdb', "FILEGDB_WORKSPACE", "Trails_Sentiers", validate=False)
    mxd.save()

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