2

I have code to change the path of a shapefile with a specific name. When it finds the same name, the path of the shapefile is changed.

This is the important part of the code:

for mxdFile in arcpy.ListFiles("*.mxd"):  
    mxdPath = env.workspace + "\\" + mxdFile  
    mxd = arcpy.mapping.MapDocument(mxdPath)
    dfList = arcpy.mapping.ListDataFrames(mxd, "*")  
    print mxdPath
    for df in dfList:  
        for lyr in arcpy.mapping.ListLayers(mxd, "", df):  
            if lyr.name == layerfile:  
                lyr.replaceDataSource(Folder, "SHAPEFILE_WORKSPACE", NewShapefile)  
                print mxdPath," - changed"
    mxd.save()
del mxd

My problem is that the script saves all the MXD in the same folder of the .py file. Not just the ones it changed.

If I put the mxd.save() under the same align of the if lyr.name == layerfile: it saves just the ones it changes. But, there is a but....

But, the script stops saving through the looping for the dataframes. It changes the first one, then saves. And then, it seems to change in all of DF, because at the it really prints mxdPath," - changed" for each df. But the save just happens at the first DF changing...

How can I fix this?

3

Your current placement for the mxd.save() is the correct one. But it has the side-effect of saving even unchanged files. A solution is to make a note of the files that have changed and then only save when changed. That can be done using a boolean flag we will called changed. The code should look something like:

for mxdFile in arcpy.ListFiles("*.mxd"):  
    mxdPath = env.workspace + "\\" + mxdFile  
    mxd = arcpy.mapping.MapDocument(mxdPath)
    dfList = arcpy.mapping.ListDataFrames(mxd, "*")  
    print mxdPath
    changed = False
    for df in dfList:  
        for lyr in arcpy.mapping.ListLayers(mxd, "", df):  
            if lyr.name == layerfile:  
                lyr.replaceDataSource(Folder, "SHAPEFILE_WORKSPACE", NewShapefile)  
                changed = True
                print mxdPath," - changed"
    if changed:
        mxd.save()
del mxd
  • Nice! I'm going to try it soon, then i'll come back here with the results. Thanks. Very nice what you did, just didnt figure why does it has the changed = False before... – raphael Jun 7 '17 at 11:35

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.