Open a Word Document Using Python

Woofer Jewper picture Woofer Jewper · Jan 14, 2019 · Viewed 16.9k times · Source

I am trying to automatically open a Word Document in Python. I am very new to programming and I heard this site helped people who had trouble with it.

I have looked at various questions and have found this:

DummyFile = path_to_docx
with open(DummyFile) as f:
    source_stream = io(f.read())
document = doc(source_stream)
source_stream.close()

But when I run it, I get:

 UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 74: character maps to <undefined>

It seems that this code is not what I want. I believe it is trying to read my document and put it into a variable. Not what I want. I want the command, that when executed, will open the word document in Microsoft Word

Expected Result:

Word Document opens in Microsoft Word, as can be seen here:

here

Answer

Robert Putt picture Robert Putt · Jan 14, 2019

The code you have posted in your question is reading the Word file into your Python code as an object you can work with rather than launching the Word application.

What you need to do is abuse the Windows' OS start command, this will launch a given file in whichever application the Windows shell has that extension registered too, for example...

os.system('start mywordfile.docx')

I don't have Word installed but I tried it like this with a PNG image file...

os.system('start mydiagram.png')

and it opened in the Photos app on Windows 10 just fine.