Skip to main content

What are the Best Python Libraries to Work with Microsoft Word?

Python is a versatile language that can be used for a wide range of applications. One area where Python shines is in working with text documents. python-docx is the best library for working with Microsoft Word documents from Python. It allows you to create, edit, and convert Word documents.

python-docx

Python-docx is a Python library that allows you to create and update Microsoft Word (.docx) files.

The library provides a comprehensive set of tools for working with docx files, including the ability to create and edit formatted text, insert images and tables, and more. Python-docx is easy to use and makes working with docx files a breeze.

Install the library

You can use the following command to install python-docx via pip.

pip install python-docx

Examples

Create new or open an existing file:

//create a new document
document = Document()
document.save('new-file-name.docx')

//open an existing document
document = Document('your-file.docx')
document.save('updated-file.docx')

Create a new docx file and write data:

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Working with python-docx', 0)

p = document.add_paragraph('My first paragraph with ')
p.add_run('bold').bold = True
p.add_run(' and ')
p.add_run('italic').italic = True
p.add_run(' text.')

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

document.save('demo.docx')

By continuing to use the site, you agree to the use of cookies.