4

I am new to python and i am trying to append new data to existing docx file using Python.

from docx import Document # for Word document 
document = Document()
document.add_paragraph('My first paragraph')
document.add_paragraph("Second paragraph")
document.add_paragraph("Third paragraph")
document.add_paragraph("fourth paragraph")
document.add_paragraph("fifth paragraph") 

document.save("testDocmod.docx")

document = Document('testDocmod.docx')
paragraphs = document.paragraphs
incr=1
for paragraph in paragraphs:
    runs = paragraph.runs
    for run in runs:
        if(incr == 2):
            run.text = 'Updatd text'
        print run.text
    incr = incr + 1

But its just updating the second element while i need to append it before second element

Ravi khatri
  • 575
  • 2
  • 5
  • 11

1 Answers1

1

Depending on whether you wish to receive you can:
1) Delete all the content of the second paragraph and re-create it:

from docx import Document
document = Document('testDocmod.docx')
paragraphs = document.paragraphs

#Store content of second paragraph
text = paragraphs[1].text

#Clear content
paragraphs[1]._p.clear()

#Recreate second paragraph
paragraphs[1].add_run('Appended part ' + text)
document.save("testDocmod.docx")

Result:

My first paragraph

Appended part Second paragraph

Third paragraph

fourth paragraph

fifth paragraph

2) Simply add text in a first paragraph:

from docx import Document
from docx.enum.text import WD_BREAK

document = Document('testDocmod.docx')
paragraphs = document.paragraphs

#Add break line after last run
paragraphs[0].runs[-1].add_break(WD_BREAK.LINE)
paragraphs[0].add_run('New text')
document.save("testDocmod.docx")

Result:

My first paragraph
New text

Second paragraph

Third paragraph

fourth paragraph

fifth paragraph
NorthCat
  • 9,643
  • 16
  • 47
  • 50
  • Thank you for the help, but suppose i have to append some images or paragraph having bullets & numbering then how to do that ? – Ravi khatri Aug 12 '14 at 13:33
  • According the docs (http://python-docx.readthedocs.org/en/latest/user/quickstart.html), you can use `add_picture()` and `paragraph.style` – NorthCat Aug 12 '14 at 14:51