Feature: Find / replace text and generally *modify* docx files
See original GitHub issueI’m doing a lot of work with existing docx (creating many docx from a template). I hacked this together but there are better ways I think, any plans to natively increase support in modifying docx? XPATH? This is my main use case.
def replace(document, search, replace):
"""Walk the tree down to w:t xml and update text node"""
searchre = re.compile(search)
count = 0
# Loop over all paras in doc
for para in document.paragraphs:
# Loop over all runs in para
for run in para.runs:
if len(run._r.t_lst) > 1:
raise
if len(run._r.t_lst) == 1:
element_wt = run._r.t_lst[0]
this_text = element_wt.text
if searchre.search(this_text):
newtext = re.sub(search, replace, this_text)
count += 1
element_wt.text = newtext
else:
continue
logging.debug("Replaced {} with {} {} times".format(search, replace, count))
Issue Analytics
- State:
- Created 10 years ago
- Comments:32 (14 by maintainers)
Top Results From Across the Web
Word 2016: Using Find and Replace - GCF Global
Word can automatically search your document using the Find feature, and it allows you to quickly change words or phrases using Replace.
Read more >Using Find & Replace in Word and Change Text Formatting ...
How to update words, phrases, and formatting that appear multiple times throughout your document quickly & easily using Find & Replace in ...
Read more >How to Find and Replace Text in Word - Nira
Step #5 Click on the Replace tab on the top menu bar. Type in the word you want to update in the Replace...
Read more >Find and Replace | Computer Applications for Managers
Find and Replace helps you to find words or formats in a document and can let you replace all instances of a word...
Read more >How to Find and Replace Text in Word: A Step-by-Step Guide
Microsoft Word's “Find and Replace” tool allows users to quickly locate specific words or phrases and replace them throughout a document, no ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

For those still looking for a solution, here is the python module you’re looking for: https://github.com/elapouya/python-docx-template
If you want to pursue, then look in the .rels file/part for the document and see which relationship points to
footer2.xml. Then find therIdof that relationship and find it in the XML for the document. Is it possible there is more than one section in the document and you’re inspecting the wrong one?