Writing data into Word documents (adding headings, images, tables)

Reading files is a breeze with the python-docx module. Now, let's shift our focus to writing Word documents. We'll perform multiple operations with documents in this section.

Getting ready

For this recipe, we will use the same fantastic Python module, python-docx. We don't need to spend much time on the setup. Let's get started!

How to do it...

  1. We start with a very basic operation of creating a .docx file and then to add a heading to it. The following code performs this operation:
            from docx import Document
            document = Document()
            document.add_heading('Test Document from Docx', 0)
            document.save('testDoc.docx')

    This is how the document looks:

  2. If you look at the screenshot, you will see ...

Get Automate it! - Recipes to upskill your business now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.