I'm trying to use the python-docx module to replace a word in a file and save the new file with the caveat that the new file must have exactly the same formatting as the old file, but with the word replaced. How am I supposed to do this?
The docx module has a savedocx that takes 7 inputs:
How do I keep everything in my original file the same except for the replaced word?
Save your documentClick FILE > Save, pick or browse to a folder, type a name for your document in the File name box, and click Save.
Go to Home > Replace. Enter the word or phrase you want to replace in Find what. Enter your new text in Replace with.
In addition to @ramil, you have to escape some characters before placing them as string values into the XML, so this worked for me:
def escape(escapee):
escapee = escapee.replace("&", "&")
escapee = escapee.replace("<", "<")
escapee = escapee.replace(">", ">")
escapee = escapee.replace("\"", """)
escapee = escapee.replace("'", "'")
return escapee
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With