Combine Word Documents using Python

Combine Word Documents in Python

There could be various scenarios when you have to combine multiple Word documents into a single file. For example, when multiple persons are writing different sections of a document and you need to combine the content at the end. On the other hand, you may need to merge all the invoices in one Word document. To perform this merging programmatically, this article covers how to combine multiple Word DOCX or DOC documents in Python.

Python Library to Combine Word Documents

To combine the DOCX or DOC files, we will use Aspose.Words for Python, which is a powerful library to create and manipulate MS Word files. It also allows you to split, combine, and convert Word documents seamlessly. You can install the library from PyPI using the following pip command.

pip install aspose-words

Combine Multiple Word DOCX Files in Python

While combining the Word documents, you can specify the formatting you want to apply to the source document. For example, when combining document B with A, you can change the formatting of B as A or keep its original formatting as it is. The following are the steps to combine two Word documents in Python.

  • Load the source Word document using Document class.
  • Load the destination Word document using Document class.
  • Combine documents by appending source document into destination document using Document.append_document(Document, aw.ImportFormatMode.KEEP_SOURCE_FORMATTING) method.
  • Select the ImportFormatMode as per your requirements.
  • Save the destination document using Document.save(string) method.

The following code sample shows how to combine two Word DOCX files in Python.

Source Document

The following is the screenshot of the source Word document we have used in this article.

source word document to combine
Source Word Document

Destination Document

The following screenshot shows the destination Word document.

destination word document to combine
Destination Word Document

Combined Document

The following is the screenshot after combining both Word documents.

combined word documents in python
Combined Word Document

Get a Free API License

Get a temporary license to use Aspose.Words for Python without evaluation limitations.

Conclusion

In this article, you have learned how to combine two Word documents in a single document using Python. You can install Aspose.Words for Python in your applications and integrate the provided code to merge Word documents. In addition to this, you can explore Aspose.Words for Python using the documentation. In case you would have any queries, you can ask us via our forum.

See Also