[GIS] Creating Loop to replace text in page layout in multiple MXDs instead of one MXD at a time

arcpypython-2.6

I found some code on a website that will perform a search and replace on page layout text elements. Currently you can only do it one MXD at a time. I was hoping to change the code so I can do a search and replace on a folder with a bunch of MXDs in it.

The script is below. I know I need a loop, just not sure how to do it; never programmed before.

import arcpy, string, os 

#Read input parameters from script tool
Path = arcpy.GetParameterAsText(0)
oldText = arcpy.GetParameterAsText(1)
newText = arcpy.GetParameterAsText(2)
case = arcpy.GetParameter(3)
exact = arcpy.GetParameter(4)
outputMXD = arcpy.GetParameterAsText(5)

try:
    #Referent the map document
    mxd = arcpy.mapping.MapDocument(mxdPath)         

    #Find all page layout text elements
    for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):     
        if exact:
            if case:
                if oldText == elm.text:
                    elmText = elm.text.replace(oldText, newText)
                    elm.text = elmText
            else:
                if oldText.upper() == elm.text.upper():
                    elmText = elm.text.upper().replace(oldText, newText)
                    elm.text = elmText   
        else:
            if case:
                if oldText in elm.text:
                    elmText = elm.text.replace(oldText, newText)
                    elm.text = elmText
            else:
                if oldText.upper() in elm.text.upper():
                    elmText = elm.text.upper().replace(oldText, newText)
                    elm.text = elmText                  
    mxd.saveACopy(outputMXD)

    del mxd

except Exception, e:
    import traceback
    map(arcpy.AddError, traceback.format_exc().split("\n"))
    arcpy.AddError(str(e))

Best Answer

The Updating and fixing data sources with arcpy.mapping help topic has an example of how to loop through .mxd's in a folder (as well as other useful arcpy examples) but my preference for how to do this would be to use glob. Something like this:

import glob
mxdList = glob.glob('*.mxd')
for mxd in mxdList:
    <put everything from your try/except block here>

This assumes your script runs from the folder where you have all your .mxd's. You could also organize this a bit better with a few functions but that's probably beyond the scope of this question.

Related Question