问题
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:
回答1:
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.
回答2:
On Windows, you can use os.startfile:
import os
os.startfile('C:\\Path\\To\\file.docx')
For other operating systems, see this answer: https://stackoverflow.com/a/435669/101087
来源:https://stackoverflow.com/questions/54185488/open-a-word-document-using-python