Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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))
share|improve this question
2  
Have a look at stackoverflow.com/questions/3207219/… –  Matthew Snape Feb 1 '11 at 12:04

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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