Mathew K Analytics

Lesson 1 · Python Libraries

Comprehensive Guide to Automating Word Documents with python-docx in Python

python-docx is a Python library for creating and editing Microsoft Word (.docx) documents. It is used to automate document creation, fill templates, or…

⬇ Download notebookOpen in Colab ↗
python-docx

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Introduction to python-docx#

  • python-docx is a Python library for creating and editing Microsoft Word (.docx) documents.
  • It is used to automate document creation, fill templates, or extract data from Word files.
  • Real world uses include automated report generation, mail merges, and filling forms.
  • With python-docx, you can make Word documents from scratch, edit existing ones, or extract text and tables easily.
# To install python-docx on Windows, run this command in your terminal or command prompt:
# pip install python-docx
from docx import Document

Core Concepts in python-docx#

  • Document object: represents an entire Word document.
  • Paragraphs and Runs: Paragraph contains text. Runs are spans with the same style.
  • Sections: control page setup.
  • Tables: add structured data.
  • Styles: control formatting for paragraphs and runs.
# BASIC EXAMPLES
# Create a new Document object
doc = Document()
print('Created a new empty Document.')
Created a new empty Document.
# Add a heading to the document
doc.add_heading('My First Document', level=1)
print('Added a heading.')
Added a heading.
# Add a paragraph
para = doc.add_paragraph('This is my first paragraph using python-docx!')
print('Added a paragraph.')
Added a paragraph.
# Save the document
doc.save('example_basic.docx')
print('Saved the document as example_basic.docx')
Saved the document as example_basic.docx
# Add multiple paragraphs
for i in range(3):
    doc.add_paragraph(f'This is paragraph {i + 1}.')
print('Added three more paragraphs.')
Added three more paragraphs.
# Save updated document
doc.save('example_basic2.docx')
print('Saved updated document as example_basic2.docx')
Saved updated document as example_basic2.docx
# INTERMEDIATE EXAMPLES
# Add a bold run to a paragraph
para2 = doc.add_paragraph()
run = para2.add_run('This is bold text.')
run.bold = True
print('Added a bold run to the document.')
Added a bold run to the document.
# Add an italic run to the same paragraph
run2 = para2.add_run(' Now some italic text.')
run2.italic = True
print('Added italic text to the same paragraph.')
Added italic text to the same paragraph.
# Add a bulleted list
doc.add_paragraph('Item one', style='List Bullet')
doc.add_paragraph('Item two', style='List Bullet')
doc.add_paragraph('Item three', style='List Bullet')
print('Added a bulleted list.')
Added a bulleted list.
# Add a numbered list
doc.add_paragraph('First', style='List Number')
doc.add_paragraph('Second', style='List Number')
doc.add_paragraph('Third', style='List Number')
print('Added a numbered list.')
Added a numbered list.
# Save after adding formatting and lists
doc.save('example_formatting.docx')
print('Saved document with formatted text and lists.')
Saved document with formatted text and lists.
# INTERMEDIATE: Working with tables
table = doc.add_table(rows=2, cols=2)
table.cell(0, 0).text = 'Name'
table.cell(0, 1).text = 'Age'
table.cell(1, 0).text = 'Alice'
table.cell(1, 1).text = '28'
print('Added a 2 by 2 table.')
Added a 2 by 2 table.
# Save the document with the table
doc.save('example_table.docx')
print('Saved document with a table as example_table.docx.')
Saved document with a table as example_table.docx.
# INTERMEDIATE: Open and read an existing document
doc2 = Document('example_table.docx')
for para in doc2.paragraphs:
    print(para.text)
My First Document
This is my first paragraph using python-docx!
This is paragraph 1.
This is paragraph 2.
This is paragraph 3.
This is bold text. Now some italic text.
Item one
Item two
Item three
First
Second
Third
# ADVANCED EXAMPLES
# Change page orientation
from docx.enum.section import WD_ORIENT
section = doc.sections[-1]
section.orientation = WD_ORIENT.LANDSCAPE
section.page_width, section.page_height = section.page_height, section.page_width
print('Changed orientation to landscape.')
Changed orientation to landscape.
# Save after orientation change
doc.save('example_landscape.docx')
print('Saved document with landscape orientation.')
Saved document with landscape orientation.
# Advanced: Add an image
doc.add_picture('mat-analytics.png', width=None, height=None)
print('Added an image to the document.')
Added an image to the document.
# Save document with image
doc.save('example_image.docx')
print('Saved document with the image as example_image.docx.')
Saved document with the image as example_image.docx.
# Advanced: Set custom font size and color
from docx.shared import Pt, RGBColor
p = doc.add_paragraph()
run = p.add_run('Custom font size and color!')
run.font.size = Pt(18)
run.font.color.rgb = RGBColor(0x42, 0x24, 0xE9)
print('Added run with custom size and color.')
Added run with custom size and color.
# Save custom style document
doc.save('example_style.docx')
print('Saved document with custom styles as example_style.docx.')
Saved document with custom styles as example_style.docx.
# ERROR HANDLING: Try opening a missing file
try:
    Document('missing.docx')
except Exception as e:
    print('Error:', e)
Error: Package not found at 'missing.docx'
# Handle runtime errors in document generation
try:
    doc.add_picture('not_a_real_picture.png')
except Exception as e:
    print('Could not add picture:', e)
Could not add picture: [Errno 2] No such file or directory: 'not_a_real_picture.png'

Best Practices and Common Patterns#

  • Always save your document after making changes.
  • Use try-except blocks for error handling.
  • Check if files exist before opening them.
  • Use meaningful file names to keep your work organized.
  • Explore the python-docx documentation for more advanced features.
# TINY MINI-PROJECT: Create a contact list
contacts = [('John', 'john@email.com'), ('Sally', 'sally@email.com')]
doc_proj = Document()
doc_proj.add_heading('Contact List', level=1)
table = doc_proj.add_table(rows=1, cols=2)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Name'
hdr_cells[1].text = 'Email'
for name, email in contacts:
    row_cells = table.add_row().cells
    row_cells[0].text = name
    row_cells[1].text = email
doc_proj.save('contacts_project.docx')
print('Mini-project document created!')
Mini-project document created!

Next Steps and Extra Resources#

  • Try making your own templates.
  • Review the python-docx official documentation for extra features.
  • Practice by automating your daily reporting tasks.

Like and Subscribe#

  • If you enjoyed this video, give it a thumbs up!
  • Subscribe to the channel for more Python tutorials.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.