Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python打开Word文档_Python_Python 3.x_Docx - Fatal编程技术网

使用Python打开Word文档

使用Python打开Word文档,python,python-3.x,docx,Python,Python 3.x,Docx,我正在尝试用Python自动打开Word文档。我对编程非常陌生,我听说这个网站帮助了有困难的人 我研究了各种问题,发现: DummyFile = path_to_docx with open(DummyFile) as f: source_stream = io(f.read()) document = doc(source_stream) source_stream.close() 但当我运行它时,我得到: UnicodeDecodeError: 'charmap' codec c

我正在尝试用Python自动打开Word文档。我对编程非常陌生,我听说这个网站帮助了有困难的人

我研究了各种问题,发现:

DummyFile = path_to_docx
with open(DummyFile) as f:
    source_stream = io(f.read())
document = doc(source_stream)
source_stream.close()
但当我运行它时,我得到:

 UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 74: character maps to <undefined>
UnicodeDecodeError:“charmap”编解码器无法对位置74中的字节0x90进行解码:字符映射到
看来这个代码不是我想要的。我相信它是在试图读取我的文档并将其放入变量中。不是我想要的。我想要一个命令,当执行该命令时,将在Microsoft word中打开word文档

预期结果:

Word文档在Microsoft Word中打开,如下所示:


您在问题中发布的代码是将Word文件作为可以使用的对象读入Python代码,而不是启动Word应用程序

您需要做的是滥用Windows的OS start命令,这将在Windows shell已注册该扩展名的任何应用程序中启动给定文件,例如

os.system('start mywordfile.docx')
我没有安装Word,但我用PNG图像文件试过这样做

os.system('start mydiagram.png')
在Windows 10上的照片应用程序中,它可以正常打开。

在Windows上,您可以使用:

对于其他操作系统,请参见以下答案:

这是一个很好的初学者问题。您已经清楚地阅读了关于如何提问的说明,并且在执行这些说明方面做得相当好。这是非常罕见的。欢迎来到SO!您说过“使用Python打开Word文档”(也就是说,听起来您的意思是使用某个包从Python内部访问文档),但您确实想“使用Python打开MS Word中的文档”(即调用操作系统启动运行MS Word的进程并在该进程中打开文档)。您可能需要考虑OP在变量中包含文件名。如果它有空格,则需要引号。如果参数来自用户输入,则有注入shell命令的风险。(攻击者可以执行任意命令)。
import os
os.startfile('C:\\Path\\To\\file.docx')