"""Directly exposed API functions and classes, :func:`Document` for now.Provides a syntactically more convenient API for interacting with the OpcPackage graph."""from__future__importannotationsimportosfromtypingimportIO,TYPE_CHECKING,castfromdocx.opc.constantsimportCONTENT_TYPEasCTfromdocx.packageimportPackageifTYPE_CHECKING:fromdocx.documentimportDocumentasDocumentObjectfromdocx.parts.documentimportDocumentPart
[文档]defDocument(docx: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 a file-like object. If `docx` is missing or ``None``, the built-in default document "template" is loaded. """docx=_default_docx_path()ifdocxisNoneelsedocxdocument_part=cast("DocumentPart",Package.open(docx).main_document_part)ifdocument_part.content_type!=CT.WML_DOCUMENT_MAIN:tmpl="file '%s' is not a Word file, content type is '%s'"raiseValueError(tmpl%(docx,document_part.content_type))returndocument_part.document
def_default_docx_path():"""Return the path to the built-in default .docx package."""_thisdir=os.path.split(__file__)[0]returnos.path.join(_thisdir,"templates","default.docx")