【问题标题】:Reading core_properties using python-docx使用 python-docx 读取 core_properties
【发布时间】:2016-10-09 20:05:19
【问题描述】:

我正在尝试读取 docx 文件的 last_saved_by 属性。我在 Github 和 this question 上关注了 cmets。似乎已经添加了支持,但是文档对我来说不是很清楚。

我已在我的脚本 (Notepad++) 中输入了以下代码:

import docx

document = Document()
core_properties = document.core_properties
core_properties.author = 'Foo B. Baz'
document.save('new-filename.docx')

最后我只收到一条错误消息:

NameError: name 'Document' is not defined

我不确定我哪里出错了。 :(

当我通过python本身逐行输入时,问题似乎来自第二行。

我使用的是 Python 3.4 和 docx 0.8.6

【问题讨论】:

  • 我猜是docx.Documentdocx.something.Document 而不仅仅是Document

标签: python python-3.x word-2010 python-docx


【解决方案1】:

找出我哪里出错了,对于那些想知道的人:

from docx import Document
import docx

document = Document('mine.docx')
core_properties = document.core_properties
print(core_properties.author)

我敢肯定,会有一种更简洁的方式来执行此操作(一开始导入 docx 两次似乎是多余的)——但它有效,所以我很高兴! :)

【讨论】:

  • 你的第二行是多余的,你的问题是 Document not found,但是 Document 在 docx 模块中,所以你有两个选择,一个:from docx import Document,你可以直接使用 Document("xxx") ;第二个你可以import docx 并使用docx.Document("xxxx"),但我强烈建议你使用第一个。
【解决方案2】:

如果docx 模块中你唯一需要的就是Document,那么你只需要使用

from docx import Document

如果你使用更多,你可以使用

import docx
document = docx.Document()

docx 模块导入特定名称是您的选择;无论哪种方式,您都不需要需要docx 导入(或导入)两行,尽管两者兼而有之并不昂贵。

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多