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.
If you have LibreOffice installed, you can call it directly with
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
Beware, you must close open instances of LibreOffice before running this, or it will exit silently without doing anything. This is a known bug.
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
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.