Ekanshu
Ekanshu

Reputation: 69

How can I find and replace a text in footer of word document using "Python docx"

enter image description hereI have created a word document and added a footer in that document using python docx. But now I want to replace text in the footer.

For example: I have a paragraph in footer i.e "Page 1 to 10". I want to find word "to" and replace it with "of" so my result will be "Page 1 of 10".

My code:

from docx import Document
document = Document()
document.add_heading('Document Title', 0)
section = document.sections[0]
footer = section.footer
footer.add_paragraph("Page 1 to 10")
document.save('mydoc.docx')

Upvotes: 1

Views: 8590

Answers (2)

sharder
sharder

Reputation: 141

I know this is an old question however the accepted answer changes the page number of the footer and requires editing of the XML if you want to fix that issue. Instead I have found that if you edit the text using Runs, it will keep the original format for your header/footer. https://python-docx.readthedocs.io/en/latest/api/text.html#docx.text.run.Run

from docx import Document
document = Document('mydoc.docx')
for section in document.sections:
    footer = section.footer
    footer.paragraphs[1].runs[0].text  = footer.paragraphs[1].runs[0].text.replace("to", "of")

document.save('mydoc.docx') 

Upvotes: 1

mbbce
mbbce

Reputation: 2303

Try this solution. You would have to iterate over all the footers in document

from docx import Document
document = Document('mydoc.docx')
for section in document.sections:
    footer = section.footer
    footer.paragraphs[1].text  = footer.paragraphs[1].text.replace("to", "of")

document.save('mydoc.docx') 

The reason why this code is editing the second element of the footer paragraphs list is because you have added another paragraph to the footer in your code. By default there is an empty paragraph already in the footer according to the documentation

Upvotes: 3

Related Questions