Python docx – Writing to a Word document

In this write up we will be going through the adding of paragraphs via Python. The script takes input and writes a new paragraph each time.

To begin with we import the docx library and the initiate a new document (This is a Word docx file with no content). We then make use of the ‘add_heading()’ method which will place a heading along the very top of our blank document in this case containing the text ‘Python Transcript’.

Using a while loop we take our user input and make use of the ‘document.add()’ method which add the input as a new paragraph within the document. The document is then saved before the user can enter in another entry.

Full source code found below:

from docx import Document

document = Document()
document.add_heading('Python Transcript', 0)

while 1 == 1:
    Input = input("Please enter your text: ")
    p = document.add_paragraph(Input)"Document.docx")

Leave a Reply