If you want to do mail merge of docx files using Python, you can use the docx-mailmerge2 package to do so.

First, start with installing the package:

$ pip install docx-mailmerge2

Once installed, using it is as easy as this:

from mailmerge import MailMerge
with MailMerge('input.docx',
        remove_empty_tables=False,
        auto_update_fields_on_open="no",
        keep_fields="none") as document:
    print(document.get_merge_fields())
    document.merge(field1='docx Mail Merge',
               field2='Can be used for merging docx documents')
    document.write('output.docx')

This approach is perfect for dynamically generating documents like reports, letters, or invoices with minimal effort. The code snippet demonstrates the entire process, replacing fields field1 and field2 in the template with specified values and saving the result as output.docx.

source