I ran your code, and sure enough, it runs fine the first time but fails after that. Not only that, but if I try to open the mxd that has gone through the process, I can't save it in Arcmap. All I can do is a Save a Copy. At this point the mxd can't quite figure out what its name is and is for all practicable purposes corrupt. Seems like a bug to me.That said, the code below will work repeatedly if you can work it into your process. The issue was the filesystem calls os.rename and os.remove. So we just do it all with arcpy:
originalDoc = r'C:\temp\Untitled.mxd'
# Make a new MXD Name...
baseFldr = os.path.dirname(originalDoc)
baseName = os.path.basename(originalDoc)
newDoc = os.path.join(baseFldr,"temp123_" + baseName)
# Open the original Document, and save a copy
mxd = arcpy.mapping.MapDocument(originalDoc)
mxd.saveACopy(newDoc)
mxd = arcpy.mapping.MapDocument(newDoc)
mxd.saveACopy(originalDoc)
mxd = None
This will be slower than what you were trying to do if the mxd's are large, as you said. The basic issue is the mixing of filesystem calls and saveACopy. Probably the fastest way to handle your work flow is eliminate the saveACopy calls completely. Something like this:
originalDoc = r'C:\temp\Untitled.mxd'
# Make a new MXD Name...
baseFldr = os.path.dirname(originalDoc)
baseName = os.path.basename(originalDoc)
old_doc = os.path.join(baseFldr,"orig_" + baseName)
# make a copy of the original with a new name
shutil.copy2(originalDoc, old_doc)
# Open the original Document, do the work, and set work_done flag
mxd = arcpy.mapping.MapDocument(originalDoc)
# do some work here if necessary, set flag depending on if
#anything was done or not. We'll set to true for demonstration
work_done = True
if work_done:
mxd.save()
# move the original to an archive folder
afol = r'C:\temp\Archive'
dest = os.path.join(afol, baseName)
shutil.move(old_doc, dest)
else:
os.remove(old_doc)
mxd = None
good luck,Mike