1

I am trying to replacing the text using loop on doc.paragrapgh .I got success in replacing the text ,but the images got removed .I want to preserve the images and only want to replace the text . Thanks in advance i am using below code for the same

from docx import Document
from docx.table import _Cell

doc = Document("abc.docx")
for p in doc.paragraphs:
    if 'CORREDOR' in p.text:
        text = p.text.replace(p.text, "VIGENCIA").strip()
        style = p.style
        p.text = text
        p.style = style
    elif 'DECLARACIÓN DE NO SINIESTRALIDAD' in p.text:
        text=  p.text.replace(p.text, "DECLARACIÓN DE  SINIESTRALIDAD")
        style = p.style
        p.text = text
        p.style = style

doc.save('result4.docx')
  • What sort of image is it? is it a link in the docx? –  Feb 08 '21 at 17:59
  • Check out the solutions in this answer, especially the first one: https://stackoverflow.com/a/24813382/1902513. What is happening is that _reading_ `paragraph.text` gives you only the text in the paragraph (skipping over any images) but _setting_ `paragraph.text` replaces _all_ the content of the paragraph, including both text and inline images. The proposed `paragraph_replace_text()` function acts with much more precision. – scanny Dec 22 '21 at 21:38

1 Answers1

0

Save into the same name (ie: doc.save('abc.docx')) is likely to fix your problem.

Or you could do a copy of your file (eg: shutil.copy('abc.docx', 'result4.docx')) before editing it with docx.

OlivierM
  • 2,820
  • 24
  • 41