Create and Edit Word Documents with Python and python-docx
python-docx lets you create, read and modify .docx files (Word) from Python without needing Microsoft Word installed — perfect for automated reports, contracts and invoices.
Installation
pip install python-docx
Create a Basic Document
from docx import Document
from docx.shared import Pt, Cm, RGBColor
doc = Document()
# Main heading
doc.add_heading("Sales Report 2024", level=1)
# Plain paragraph
doc.add_paragraph("This report summarizes sales for fiscal year 2024.")
# Formatted paragraph
p = doc.add_paragraph()
run = p.add_run("Result: ")
run.bold = True
run.font.size = Pt(12)
p.add_run("We exceeded the target by 15%.")
doc.save("report.docx")
print("Document created: report.docx")
Styles and Text Formatting
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = Document()
for level in range(1, 4):
doc.add_heading(f"Heading Level {level}", level=level)
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run("Important text in red")
run.font.color.rgb = RGBColor(0xFF, 0x00, 0x00)
run.font.size = Pt(14)
run.bold = True
run.italic = True
doc.add_paragraph("First item", style="List Bullet")
doc.add_paragraph("Second item", style="List Bullet")
doc.add_paragraph("Step one", style="List Number")
doc.add_paragraph("Step two", style="List Number")
doc.save("formatted.docx")
Insert Tables
from docx import Document
doc = Document()
doc.add_heading("Product Table", level=2)
data = [
["Product", "Price", "Stock"],
["Widget A", "9.99", "150"],
["Widget B", "24.99", "80"],
["Widget C", "4.99", "320"],
]
table = doc.add_table(rows=len(data), cols=3)
table.style = "Table Grid"
for i, row in enumerate(data):
for j, cell_text in enumerate(row):
cell = table.cell(i, j)
cell.text = cell_text
if i == 0: # Bold header row
cell.paragraphs[0].runs[0].bold = True
doc.save("table.docx")
Insert Images and Page Breaks
from docx import Document
from docx.shared import Cm
doc = Document()
doc.add_heading("Cover Page", level=1)
try:
doc.add_picture("logo.png", width=Cm(6))
except FileNotFoundError:
doc.add_paragraph("[image not found]")
doc.add_page_break()
doc.add_heading("Content", level=1)
doc.add_paragraph("The main content begins here.")
doc.save("with_image.docx")
Read and Extract Text from DOCX
from docx import Document
def extract_text_docx(path):
doc = Document(path)
lines = []
for para in doc.paragraphs:
if para.text.strip():
lines.append(para.text)
for table in doc.tables:
for row in table.rows:
row_text = [cell.text.strip() for cell in row.cells]
lines.append(" | ".join(row_text))
text = "\n".join(lines)
with open("extracted_text.txt", "w", encoding="utf-8") as f:
f.write(text)
print(f"Extracted {len(lines)} paragraphs")
return text
extract_text_docx("report.docx")
Generate Documents from a Template
from docx import Document
def fill_template(template_path, output_path, replacements):
doc = Document(template_path)
for para in doc.paragraphs:
for key, value in replacements.items():
if key in para.text:
for run in para.runs:
if key in run.text:
run.text = run.text.replace(key, str(value))
doc.save(output_path)
print(f"Document generated: {output_path}")
fill_template("contract_template.docx", "contract_john.docx", {
"{{NAME}}": "John Smith",
"{{DATE}}": "April 25, 2024",
"{{AMOUNT}}": "$1,500.00",
"{{COMPANY}}": "TechSolutions Inc.",
})
Additional Resource
For converting DOCX files to PDF, ODT or TXT without any coding, use KaijuConverter — free and no registration required.
Related conversions
Document conversions that follow this topic naturally: