簡體   English   中英

python docx:AttributeError:“函數”對象沒有屬性“ add_paragraph”

[英]python docx: AttributeError: 'function' object has no attribute 'add_paragraph'

剛開始學習python,現在我需要python docx函數的幫助。
我正在使用python v3.5.1

那就是我想從.py文件運行的代碼:

from docx import Document
document = Document
paragraph = document.add_paragraph('I am adding a new paragraph here.')
document.save('test-thu18feb-b.docx')

按F5后,我在python shell中收到以下消息:

Traceback (most recent call last):
File "C:/Users/Schauer/AppData/Local/Programs/Python/Python35/docx-
test-thu18feb-a.py", line 4, in <module>
paragraph = document.add_paragraph('I am adding a new paragraph here.')
AttributeError: 'function' object has no attribute 'add_paragraph'

非常感謝您的幫助!

該聲明

document = Document

功能docx.Document分配給document

document = Document()

將函數docx.Document 返回的值分配給document 您需要后者。


docx.Document構造函數 它返回docx.document.Document類的實例。


根據docs ,這是docx.Document函數的定義:

def Document(docx=None):
    """
    Return a |Document| object loaded from *docx*, where *docx* can be
    either a path to a ``.docx`` file (a string) or a file-like object. If
    *docx* is missing or ``None``, the built-in default document "template"
    is loaded.
    """
    docx = _default_docx_path() if docx is None else docx
    document_part = Package.open(docx).main_document_part
    if document_part.content_type != CT.WML_DOCUMENT_MAIN:
        tmpl = "file '%s' is not a Word file, content type is '%s'"
        raise ValueError(tmpl % (docx, document_part.content_type))
    return document_part.document

因此docx.Document是一個函數,而docx.document.Document是一個類。 由於您導入

from docx import Document

Document是指代碼中的docx.Document

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM