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
There are a couple of ways that you can go. If all the date text contains the address info, you could replace the entire contents with the similar contents that include dynamic text for the date.
If the print date line is separated by new line codes \n, you can split your old text, replace the part with the print date and rejoin the text. It appears that your text might follow this pattern. If so, you can try something like this:
If the date text that you want replaced is on the same line with other text ( such as: Print Date: 11/28/2018 By: JP ) then you may need to consider an alternative like regular expressions if a pattern in the text cannot be found. There is a discussion on stackoverflow ( Extracting date from a string in Python ) that would be of interest if you need another option.