可以使用python-docx的Document类中的element属性来判断文档格式,因为element属性返回的是文档的XML元素,不同格式的文档其元素名称不同。

具体实现方法如下:

from docx import Document

def determine_doc_format(file_path):
    doc = Document(file_path)
    if doc.element.tag.endswith('word/document'):
        return 'docx'
    elif doc.element.tag.endswith('word/document.xml'):
        return 'doc'
    else:
        return 'unknown'

上述代码中,先使用Document类加载文档,然后通过element属性获取文档的XML元素标签。如果标签以'word/document'结尾,则说明文档是docx格式;如果标签以'word/document.xml'结尾,则说明文档是doc格式;否则返回'unknown'表示无法判断。

需要注意的是,这种方法的前提是文档本身是可读的,如果文档损坏或者无法打开,则无法使用此方法判断格式


原文地址: https://www.cveoy.top/t/topic/c3Yj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录