Python libmagic bindings

1.0 · active · verified Fri Apr 17

libmagic provides Python bindings to the `libmagic` C library, which identifies file types by checking their 'magic numbers' and other patterns. It's a thin wrapper around the venerable `file` command-line utility. The current version is 1.0, and it generally follows a stable, low-cadence release cycle focusing on maintenance and compatibility with the underlying C library.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `libmagic` to identify file types from both actual files and byte buffers. It also shows how to retrieve the MIME type. A crucial first step not shown here is installing the underlying C `libmagic` library.

import os
from magic import Magic

# Create a dummy file for demonstration
dummy_file_path = "test_file_for_libmagic.txt"
with open(dummy_file_path, "w") as f:
    f.write("This is a plain text file content.")

try:
    # Initialize Magic - often detects libmagic automatically
    # If not, you might need to specify the path to your magic.mgc file:
    # m = Magic(magic_file='/usr/share/misc/magic.mgc')
    m = Magic()

    # Get file type description from a file
    file_description = m.from_file(dummy_file_path)
    print(f"File '{dummy_file_path}' description: {file_description}")

    # Get file type from a byte buffer
    buffer_data = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR..."
    buffer_description = m.from_buffer(buffer_data)
    print(f"Buffer data description: {buffer_description}")

    # Get MIME type explicitly
    m_mime = Magic(mime=True)
    mime_type = m_mime.from_file(dummy_file_path)
    print(f"File '{dummy_file_path}' MIME type: {mime_type}")

finally:
    # Clean up the dummy file
    if os.path.exists(dummy_file_path):
        os.remove(dummy_file_path)

view raw JSON →