You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让python-magic正确识别docx文件类型而非application/zip?

检测MS Office OOXML文件类型的解决方案

因为OOXML格式的MS Office文件(docx/xlsx/pptx)本质是zip包,magic库会直接识别为application/zip,你可以通过分析zip包内的特征目录来判断具体类型,同时验证是否为单个合法的Office文件:

核心思路

OOXML文件有固定的目录结构:

  • docx文件包含顶级目录word/
  • xlsx文件包含顶级目录xl/
  • pptx文件包含顶级目录ppt/

同时,所有OOXML文件都会包含[Content_Types].xml核心文件,且顶级目录/文件只会是特征目录、_rels/、docProps/(可选)和[Content_Types].xml,不会有额外的无关内容(以此确保是单个Office文件,而非打包的zip)。

实现代码

import zipfile

def get_ooxml_mime_type(file_path):
    try:
        with zipfile.ZipFile(file_path, 'r') as zf:
            # 检查是否为OOXML基础结构
            if '[Content_Types].xml' not in zf.namelist():
                return None
            
            # 检测特征目录,判断具体类型
            has_word = any(name.startswith('word/') for name in zf.namelist())
            has_xl = any(name.startswith('xl/') for name in zf.namelist())
            has_ppt = any(name.startswith('ppt/') for name in zf.namelist())
            
            # 验证是否为单个合法文件(无额外顶级内容)
            top_level_items = {item.split('/')[0] for item in zf.namelist()}
            if has_word:
                allowed = {'word', '_rels', 'docProps', '[Content_Types].xml'}
                if top_level_items.issubset(allowed):
                    return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            elif has_xl:
                allowed = {'xl', '_rels', 'docProps', '[Content_Types].xml'}
                if top_level_items.issubset(allowed):
                    return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            elif has_ppt:
                allowed = {'ppt', '_rels', 'docProps', '[Content_Types].xml'}
                if top_level_items.issubset(allowed):
                    return 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
            
            # 不符合标准单个Office文件的情况
            return None
    except zipfile.BadZipFile:
        # 不是有效的zip文件
        return None

使用说明

  • 调用该函数,传入文件路径,会返回对应的MIME类型,返回None则表示不是合法的单个OOXML文件
  • 可以结合magic库的结果先过滤出application/zip类型的文件,再用这个函数进一步识别,提升效率

内容的提问来源于stack exchange,提问作者tthheemmaannii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 20:05:25