python-docx

python-docx creates, reads and updates Word .docx files from Python. Good for simple documents, with 1 font trap. In NicAI it is 1 of 4 ways to make a .docx, and rarely the first.

python-docx is a Python library for Word documents in the .docx format. It gives you an object model (document, paragraphs, runs, tables, sections, styles) over the OOXML package, so you never touch the XML for everyday work.

Steve Canny wrote it. MIT licence, Python 3.9+. The latest release is 1.2.0, from 16th June 2025. It is the same author's sibling of python-pptx.

What it does well

  • New documents from code: headings, paragraphs, bold and italic runs, tables, images, page breaks, sections and margins.
  • Start from a template. Open a .docx that already holds your styles, header and footer, delete its body, write yours. The branding comes from the template, not from code.
  • Read documents: walk the paragraphs and tables of a file someone sent you.
  • Small edits to an existing file, when the text sits in plain paragraphs.

Install and use

pip install python-docx      # the import name is docx
from docx import Document
from docx.shared import Pt, Cm

doc = Document("template.docx")          # or Document() for Word's default template
doc.add_heading("Quarterly review", level=1)
p = doc.add_paragraph("Pipeline grew ")
p.add_run("18%").bold = True
p.add_run(" in Q3.")

table = doc.add_table(rows=1, cols=2, style="Table Grid")
table.rows[0].cells[0].text = "Metric"
table.rows[0].cells[1].text = "Value"

doc.add_picture("chart.png", width=Cm(15))
doc.save("review.docx")

Limits

  • No table of contents, footnotes or tracked changes in the API. A TOC is a field you insert as raw XML, and Word fills it on open.
  • No rendering. python-docx can't show you the page or make a PDF. You need Word, LibreOffice or another renderer to see the result.
  • Text replacement is fragile. Word splits a sentence into several runs (spelling marks, formatting changes), so a simple find-and-replace often misses.
  • Slow releases. 1.2.0 is 17 months old. It works, but don't expect new features.

Gotchas

⚠️ WARNING: Setting style.font.name isn't enough for headings. The built-in heading styles carry theme font attributes (w:asciiTheme, w:hAnsiTheme, w:eastAsiaTheme, w:cstheme) that Word prefers over the explicit font. Your headings silently fall back to Calibri Light. Strip those attributes from every style.

from docx.oxml.ns import qn

def force_font(doc, font_name: str) -> None:
    """Set 1 font on every style and remove the theme fonts Word would prefer."""
    for style in doc.styles:
        rpr = style.element.find(qn("w:rPr"))
        if rpr is None:
            continue
        rfonts = rpr.find(qn("w:rFonts"))
        if rfonts is None:
            continue
        for attr in ("w:asciiTheme", "w:hAnsiTheme", "w:eastAsiaTheme", "w:cstheme"):
            rfonts.attrib.pop(qn(attr), None)
        for attr in ("w:ascii", "w:hAnsi", "w:cs"):
            rfonts.set(qn(attr), font_name)
  • Fonts aren't embedded. The document names a font; the reader's machine must have it.
  • Test every file by opening it. soffice --headless --convert-to pdf file.docx is a cheap check: if LibreOffice renders it, Word will open it.

How I use it in NicAI

python-docx is 1 tool among 4, picked by the job. My agents generate Word files for my B2B work (reports, briefs, proposals on request) and personal documents.

Job What NicAI uses
Markdown on the clipboard to a branded .docx Pandoc with a reference document taken from my Word template, see Convert Markdown files to Microsoft Word
A full branded document (cover, TOC, footer) A build script that writes the OOXML directly from a Markdown source
A simple document from data python-docx
A change to a .docx a human already edited WordCraft, headless, with tracked changes if needed, see WordCraft

Why python-docx isn't the default: my branded documents need a real table of contents, footnotes and exact fonts, which means raw XML anyway. Writing the XML directly from 1 template keeps every document identical. python-docx stays the quick option for a plain document built from a table of data.

The rule that matters most: once a human edits the Word file, it is the source. The agent never regenerates it from Markdown, because that would wipe the edits. It edits the file in place instead.

Every .docx gets 2 checks before I see it: a LibreOffice PDF conversion, and page renders from WordCraft that the agent reads as images.

Further reading

NicAI
Written by NicAI, Nic's AI assistant, for his personal knowledge base. Researched and drafted by the model, not hand-written by Nic. Verify anything you plan to act on.