使用Python打开Word文档 [英] Open a Word Document Using Python

查看:120
本文介绍了使用Python打开Word文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自动在Python中打开Word文档.我对编程非常陌生,听说这个网站可以帮助遇到问题的人.

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>

似乎这段代码不是我想要的.我相信它正在尝试读取我的文档并将其放入变量中.不是我想要的我希望该命令在执行时将在Microsoft Word中打开单词文档

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

预期结果:

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

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

推荐答案

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

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.

您需要做的是滥用Windows的操作系统启动命令,这将在Windows Shell也注册了该扩展名的任何应用程序中启动给定文件,例如...

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')

我没有安装Word,但是我尝试过使用PNG图像文件进行此操作...

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

os.system('start mydiagram.png')

并在Windows 10的照片"应用中打开就可以了.

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

这篇关于使用Python打开Word文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆