Jan Jan - 25 days ago 23
Python Question

Python docx: insert_after()?

Right now, I have a "template file" where several paragraphs exist (like education, career, aims, etc.) and every paragraph is composed like

1. Education

2. Career

3. Aims




Now, I'd like to fill these paragraphs with text from a database to make it look like

1. Education
some education text from the database

2. Career
some nasty career stuff from the database

3. Aims
some aims defined here from the database




I searched through the API documentation but found only a close function called
insert_paragraph_before(text)
- does the counterpart exist?


The desired output should be:

from docx import Document
document = Document('template.docx')
for p in document.paragraphs:
if p.text == 'some keyword here':
p.insert_paragraph_after('some text to insert here')
^
|
function does not (yet?) exist

document.save('result.docx')

Answer

The short answer is "not yet".

What you might be able to do is something like this though:

def insert_paragraph_after(paragraphs, idx, text=None):
    next_paragraph_idx = idx + 1
    if idx == len(paragraphs):
        return document.add_paragraph(text)
    next_paragraph = paragraphs[next_paragraph_idx]
    return next_paragraph.insert_paragraph_before(text)

paragraphs = list(document.paragraphs)
for idx, paragraph in enumerate(paragraphs):
    if paragraph.text == 'some keyword':
        insert_paragraph_after(paragraphs, idx, "Some lorem ipsum here")
Comments