4

I need to convert .doc files to .docx within my code itself . I have done it using comtypes.client but this library basically requires Windows and Microsoft Word to be installed . What would be the best package in python that could do the conversion without the need of windows and office word. Pandoc looks good but it doesn't support .doc files.

3 Answers 3

3

If you have LibreOffice installed, you can call it directly with subprocess:

import subprocess
import os

for filename in os.listdir(os.getcwd()):
    if filename.endswith('.doc'):
        subprocess.call(['soffice', '--headless', '--convert-to', 'docx', filename])

This will convert all the files in the current directory with names ending in .doc to .docx format.

Beware, you must close open instances of LibreOffice before running this, or it will exit silently without doing anything. This is a known bug.

https://bugs.documentfoundation.org/show_bug.cgi?id=37531

1

You could use unoconv and convert the files through LibreOffice. It is imperfect, and some formatting is lost, but it will convert all doc files to docx with

unoconv -d document --format=docx *.doc
0

Spire.Doc for Python (commercial) can be used to convert between .doc and .docx formats. It eliminates the need for Microsoft Word or other external software.

Here is the pip command for installing it:

pip install Spire.Doc

Here is an example that converts .doc to .docx:

from spire.doc import *
from spire.doc.common import *

# Create an object of the Document class
document = Document()
# Load a Word DOC file
document.LoadFromFile("Sample.doc")

# Save the DOC file to DOCX format
document.SaveToFile("ToDocx.docx", FileFormat.Docx2016)
# Close the Document object
document.Close()

More details can be found in this blog post: Convert Word DOCX to DOC or DOC to DOCX with Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.