How to read a Word Document?

python-docx reads and writes Word documents (.docx).

A straightforward library to access documents in MS Word format. Available features include text, labeled sections, pictures and tables.

Install it with:

pip install python-docx

The following code reads the document in hamlet.docx:


from docx import Document

document = Document('hamlet.docx')

for para in document.paragraphs:
    print(para.text)

How to write a Word Document?

Writing a Word document is not very complicated either:


# Create a Word document:

from docx import Document

d = Document()

d.add_heading('Hamlet')
d.add_heading('dramatis personae', 2)
d.add_paragraph('Hamlet, the Prince of Denmark')

d.save('hamlet.docx')

Hint

With python-docx it is possible to read a word document, modify the content and write the result without losing existing format information.