[GIS] Change ArcSDE data source for mxds in specific folder using ArcPy

arcpyenterprise-geodatabase

I've searched all the forums and help and have made progess but recently got an error that has thrown me for a loop – also some mxds are not being changed at all! What I'd like my code to do:
Iterate through mxds in a specific folder, change the ArcSDE data source in each layer within an mxd and change it to the new ArcSDE source (we just upgraded our server). Then I'd like to either save over that mxd, or save to a new folder (whatever works!).

Here's the code:

import arcpy
import os

folderPath = "G:\GIS\Services\Test"
for fileName in os.listdir (folderPath):
    fullPath = os.path.join(folderPath, fileName)
    if os.path.isfile(fullPath):
        basename, extension = os.path.splitext(fullPath)
    if extension.lower() == ".mxd":
        mxd = arcpy.mapping.MapDocument(fullPath)
        print "MXD: " + fileName
        arcpy.env.workspace = fullPath            
        mxd.replaceWorkspaces("", "NONE", r"Database Connections\Connection to gisserver.sde","SDE_WORKSPACE")        

print "successfully changed data sources"
mxd.save()
del mxd

This worked sucessfully when tested with one mxd in a folder, so i thought it would apply to a folder with more mxds, however
The error I received while attempting to iterate through the folder:

Traceback (most recent call last):
File "C:/Users/lyee/Test2", line 10, in
mxd = arcpy.mapping.MapDocument(fullPath)
File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\arcobjects\mixins.py", line 608, in init
assert (os.path.isfile(mxd) or (mxd.lower() == "current")), gp.getIDMessage(89004, "Invalid MXD filename")
AssertionError: Invalid MXD filename.

Best Answer

I googled around and I suppose you are basing off of some code found here: http://resources.arcgis.com/en/help/main/10.1/index.html#//00s30000004p000000

You'll notice that the code is slightly different with nesting the if statements and especially the location of mxd.save(). That is likely your problem unless you are using their code and I'm looking at a copy-paste formatting error. If the first if statement fails, the second one is still evaluated, which isn't what you want.

Before finding that, I wrote this:

import os, arcpy

folderPath = "G:\GIS\Services\Test"
for fileName in [x for x in os.listdir(folderPath) if os.path.splitext(x)[1] == ".mxd"]:
    fullPath = os.path.join(folderPath, fileName)
    if os.path.isfile(fullPath):          
        mxd = arcpy.mapping.MapDocument(fullPath)
        print "MXD: " + fileName
        arcpy.env.workspace = fullPath            
        mxd.replaceWorkspaces("", "NONE", r"Database Connections\Connection to gisserver.sde","SDE_WORKSPACE")        

        mxd.save()
        del mxd
    else:
        print "error! {0} failed to be replaced".format(fullPath)
print "successfully changed data sources"

I haven't tested it, but it should work.

Related Question