Search code examples
pythonpython-3.xms-wordpython-docx

I want to add a new paragraph between two existing paragraph in word file using python docx


In my word file I have

My first paragraph

My second paragraph

Third paragraph

Fourth paragraph

fifth paragraph

My Code

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

document = Document('E:\\world\\2.docx')

paragraphs = document.paragraphs

paragraphs[2].runs[-1].add_break(WD_BREAK.LINE)

document.add_paragraph('new para between existing one ')

document.save('E:\\world\\2.docx')

After the execution I get

My first paragraph

My second paragraph

Third paragraph

Fourth paragraph

fifth paragraph

new para between existing one

But I want output as

My first paragraph

My second paragraph

Third paragraph

new para between existing one

Fourth paragraph

fifth paragraph


Solution

  • You need to insert the paragraph instead of adding it. See this documentation for reference. Also more info about paragraph objects here.

    Note, you might need to change the [5] I used depending on the actual contents of the .docx you're editing.

    from docx import Document
    from docx.enum.text import WD_BREAK
    
    document = Document('E:\\world\\2.docx')
    
    paragraphs = document.paragraphs
    
    paragraphs[2].runs[-1].add_break(WD_BREAK.LINE)
    
    paragraphs[5].insert_paragraph_before('new para between existing one ')
    
    document.save('E:\\world\\2.docx')