Open a Word Document Using Python [duplicate]
Asked Answered
S

2

15

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

Signify answered 14/1, 2019 at 16:29 Comment(2)
This is a nice beginner question. You've clearly read the instructions on how to ask and done a pretty good job of carrying them out. It's surprisingly rare to see that. Welcome to SO!Longevity
You said "Open a Word Document using Python" (i.e. sounds like you mean access the document from within python, using some package), but you really want to do "Open a Document, in MS-Word, using Python" (i.e. call the OS to start a process running MS-Word and opening the document in that).Quarrier
T
13

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.

Trichome answered 14/1, 2019 at 16:36 Comment(2)
You may want to take into account that OP has the file name in a variable. If it has spaces, it'll need quotes.Longevity
If the parameter comes from user input, this has a risk of shell command injection. (Attacker can execute arbitrary commands).Atonsah
A
12

On Windows, you can use os.startfile:

import os
os.startfile('C:\\Path\\To\\file.docx')

For other operating systems, see this answer: https://mcmap.net/q/134868/-open-document-with-default-os-application-in-python-both-in-windows-and-mac-os

Atonsah answered 14/1, 2019 at 16:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.