Skip to main content
 首页 » 编程设计

Python Docx Lib之打开 Word

2024年10月25日9kerrycode

这里是新手程序员。我正在尝试学习如何打开/编辑/保存 word 文档文件。我在 windows 7 64bit 上并且有 Microsoft Word 2010。我遵循这个指南:https://python-docx.readthedocs.org/en/latest/user/quickstart.html

我正在按照第一部分“打开文档”进行操作并输入前两行,但没有打开任何内容。所以我一定做错了什么。根本无法打开word。有什么建议吗?

请您参考如下方法:

你想做什么...那就是创建一个新文档...而不是用 word 打开它

打开文件

os.startfile(r"C:\Some\Folder\doc1.docx") 

docx(您引用的 python 模块)的作用是创建新的 docx 文件,然后您可以在创建它们后用 word 打开

考虑以下内容

from docx import Document 
import os 
document = Document() #create a new document 
paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.') 
document.save('test.docx') #save it to the filesystem 
os.startfile("test.docx") #open it with the default handler for docx (usually word)