[Python] How to detect MIME type from a file buffer in Python, especially for legacy Office...

Discussão em 'Python' iniciado por Stack, Abril 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm building a general-purpose Python library for text extraction that should support input from either:

    • A file path (e.g., str pointing to a local file),

    or

    • A file-like object (e.g., BytesIO stream, such as you'd get from a web upload or in-memory operation)

    To decide which extraction function to call, I need to detect the MIME type of the file.

    Current approach I'm currently using python-magic, which wraps libmagic, like this:

    import magic

    file_input.seek(0)
    mime_type = magic.Magic(mime=True).from_buffer(file_input.read(2048))
    file_input.seek(0)


    This works well for modern formats like PDF, DOCX, XLSX, etc., but not for legacy Microsoft Office formats such as .xls, .doc, .ppt.

    For those, the detected MIME type is always:

    application/x-ole-storage


    Which means I can't distinguish between .doc and .xls from a buffer, unless I already know the original filename or extension — which may not be available (e.g., if the file is being streamed or uploaded).

    What I’ve tried or considered

    • magic.from_file(path) works well — but obviously requires a real file path
    • filetype is lightweight, but doesn't support .xls/.doc
    • mimetypes.guess_type() is extension-based — not usable with buffers
    • Using heuristics: try parsing with xlrd, or looking for streams inside the OLE2 structure
      • This works, but is fragile and a bit ugly
    • Embedding extension in metadata (e.g., as a side-channel) — not ideal for generic libraries

    ❓ The Question Is there a better way to detect the MIME type of a file given only a BytesIO buffer, especially for legacy formats like .xls, .doc, and .ppt?

    Or put differently:

    How do you build a clean, extensible MIME type detection strategy that works even in streaming or upload-based contexts, and doesn't depend on file extensions?

    Related discussions I’m aware of this classic and widely referenced post: How to find the MIME type of a file in Python

    But none of the answers there fully address the specific case of distinguishing OLE2 formats when working with in-memory buffers only.

    Thanks in advance for any insight — I'm hoping for a clean and reliable solution to integrate into an open-source Python package!

    Continue reading...

Compartilhe esta Página