AnsweredAssumed Answered

find text element in MXD with wildcard?

Question asked by jpilbeam on Nov 13, 2018
Latest reply on Dec 6, 2018 by jpilbeam

I have a working script that searches for a text element in an MXD and replaces it with new text. I'm using it to update the "print date: mo./day/year". But, this method is sort of limited in that it only finds that exact string. In my map document folder, the dates of these maps differ from each other. So, how can I make the script replace an open-ended string? 

 

I've tried:

oldText = "Print Date: "

and

oldText = "Print Date: *"

 

As the script is here, "oldText = Print Date: 9.6.2016" will be replaced with "newText = Print Date: 11/13/2018". But, dates on other maps could be anything. If I could replace the old with dynamic text date that would be even better.

 

arcpy.env.workspace = Workspace = r"path\to\TestFolder"
Output = r"path\to\TestFolder2"
oldText = "Print Date: 9.6.2016"
oldList = oldText.split(', ')
newText = "Print Date: 11/13/2018"
newList = newText.split(', ')

# list the mxds of the workspace folder
for mxdname in arcpy.ListFiles("*.mxd"):
    print "checking document: {}".format(mxdname)
# set the variable
    mxd = arcpy.mapping.MapDocument(Workspace + "\\" + mxdname)
# replace elements that occur in the map document
    for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        counter = 0
        for text in oldList:
            if text in elm.text:
                elm.text = elm.text.replace(text, newList[counter])
                print '{} changed'.format(elm.text)
                counter = counter + 1
            else:
                counter = counter + 1

    for elm in arcpy.mapping.ListLayoutElements(mxd, ""):
        counter = 0
        for text in oldList:
            if text in mxd.title:
                mxd.title = elm.text.replace(text, newList[counter])
                counter = counter + 1
            else:
                counter = counter + 1
# move the mxd.saveACopy outside of the if loop so a copy is saved even it does not meet the condition of the if loops
    mxd.save() #(os.path.join(Output + "\\" + mxdname))
# do not include this delete statement inside the above loop or it will delete the mxd object inside the loop. Make sure to dedent.
del mxd

Outcomes