Skip to content

api

api

Directly exposed API functions and classes, Document for now.

Provides a syntactically more convenient API for interacting with the OpcPackage graph.

Document

Document(
    docx: str | PathLike[str] | IO[bytes] | None = None,
) -> Document

Return a Document object loaded from docx, where docx can be either a path to a .docx file (a string or os.PathLike) or a file-like object.

Macro-enabled .docm files and Word templates — .dotx and .dotm — are also accepted. Their macro storage is preserved when the document is saved, but this library provides no API to read or modify it.

A template opened this way is still a template when saved; pass as_template=False to Document.save to write it out as an ordinary document instead.

If docx is missing or None, the built-in default document "template" is loaded.

Source code in src/docx/api.py
def Document(docx: str | os.PathLike[str] | IO[bytes] | None = None) -> DocumentObject:
    """Return a |Document| object loaded from `docx`, where `docx` can be either a path
    to a ``.docx`` file (a string or ``os.PathLike``) or a file-like object.

    Macro-enabled ``.docm`` files and Word templates — ``.dotx`` and ``.dotm`` — are
    also accepted. Their macro storage is preserved when the document is saved, but this
    library provides no API to read or modify it.

    A template opened this way is still a template when saved; pass
    ``as_template=False`` to :meth:`.Document.save` to write it out as an ordinary
    document instead.

    If `docx` is missing or ``None``, the built-in default document "template" is
    loaded.
    """
    docx = _default_docx_path() if docx is None else docx
    if isinstance(docx, os.PathLike):
        docx = os.fspath(docx)
    document_part = cast("DocumentPart", Package.open(docx).main_document_part)
    if document_part.content_type not in _WORD_MAIN_CONTENT_TYPES:
        tmpl = "file '%s' is not a Word file, content type is '%s'"
        raise ValueError(tmpl % (docx, document_part.content_type))
    return document_part.document