A guide to write word file using Python

Introduction

This tutorial shows a guide on how to write word file using Python. You know that word is great for documentation. This tutorial also shows how to install docx module when this module is not available in Python on Windows Operating System. This module is required to write word doc or docx file format using Python.

In this example, I will insert image, I will create table, text with different formats, heading, title, underline etc.

Benefits of Word Document

This word document tool is used in many areas and some of them are given below:

  • You can create all types of official documents in Microsoft Word.
  • You can create lecture script by using text, word art, shapes, colors, and images.
  • You can create a birthday card, invitation card in Microsoft Word by using pre-defined templates or using insert menu and format menus functions.
  • You can highlight basic and advance knowledge of MS Word as great skill in your resume for the job interview.
  • You can create notes and assignment on MS-word.
  • You can create and print a book using MS Word by creating a cover page, content, head and footers, image adjustments, text alignment and text highlighter etc.
  • You can start your business online and offline. You need to create documents for official works.
  • You can use Microsoft word to collaborate with your team while working on the same project and document.
  • What’s more, this software is widely used in many different application fields all over the world and it also applies to data science.

Related Posts:

You might have seen various operations on word files using wonderful API – Apache POI in Java technology and it requires few more lines of code have to be written to read from or write to word files.

But to write word file using Python is very easy with a few lines of code. I will create a simple word file here to write word file using Python.

Let’s move on to the example…

Prerequisites

Python 3.8.0 – 3.9.1, docx 0.8.10 (pip install python-docx)

Preparing Workspace

Preparing your workspace is one of the first things that you can do to make sure that you start off well. The first step is to check your working directory.

When you are working in the Python terminal, you need first navigate to the directory, where your file is located and then start up Python, i.e., you have to make sure that your file is located in the directory where you want to work from.

Required Modules

Check for modules docx in Python terminal. Type the command as shown below to check docx package. If you do not get any error message then the module exists otherwise you have to install the non-existence module.

>> import docx

If you do not have docx module available then please go through tutorial A guide to read word file using Python to install docx module in Windows Operating System.

Now let’s move on to the example write word file using Python.

In the below image you see I have opened a cmd prompt and navigated to the directory where I have put the word file that has to be written.

python docx

Write Docx File

Now create a Python script write_word.py under the C:\py_scripts for writing to the word file. Here py is extension of the Python file.

In the below Python script notice how we imported docx module.

The below Python script shows how to write word file using Python.

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)

document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph(
    'first item in unordered list', style='List Bullet'
)

document.add_paragraph(
    'first item in ordered list', style='List Number'
)

document.add_picture('write-word-using-python.jpg', width=Inches(1.25))


recordset = [
    {
        "id" : 1,
        "qty": 2,
        "desc": "New item"
    },
    {
        "id" : 2,
        "qty": 2,
        "desc": "New item"
    },
    {
        "id" : 3,
        "qty": 2,
        "desc": "New item"
    }
]
#print(recordset[0]['id'])
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Id'
hdr_cells[1].text = 'Quantity'
hdr_cells[2].text = 'Description'
for item in recordset:
	#print(item)
	row_cells = table.add_row().cells
	row_cells[0].text = str(item['id'])
	row_cells[1].text = str(item['qty'])
	row_cells[2].text = str(item['desc'])

document.add_page_break()

document.save('simple.docx')

Make sure you have the image (write-word-using-python.jpg) in the same folder as you have the Python script.

Testing the Application

When you execute the above Python script, then you should see the following word file created under the directory C:\py_scripts.

write word file using python

Hope you understood how to write word file using Python.

Source Code

Download

1 thought on “A guide to write word file using Python

Leave a Reply

Your email address will not be published. Required fields are marked *