Python-magic exposes libmagic to Python so programs can guess file types from content headers. It wraps the same logic used by the Unix file command.
Overview
Python-magic is a Python interface to the libmagic file type identification library. Libmagic classifies files by inspecting their headers against a predefined list of types, matching what the Unix file command does on the command line.
A Magic class offers direct control, including choosing the magic database file and enabling character encoding detection. Identification via fromfile, frombuffer, and fromdescriptor uses a per-instance lock so those methods are safe across threads on one instance, though concurrent setparam changes or direct cookie access are not covered.
The package is a thin wrapper over the libmagic C library, which must be installed separately on the host. Installation notes in the documentation cover Debian and Ubuntu, macOS with Homebrew or MacPorts, Windows bitness issues, and pointing to non-standard library locations with environment variables.
Historically many reported issues trace to libmagic rather than the Python layer; the project documents compatibility between these bindings and libmagic’s own Python API via a compatibility layer.
Key features
- Header-based file type detection
- Magic class with custom database path
- Optional character encoding detection
- fromfile, frombuffer, fromdescriptor APIs
- Per-instance locking for thread-safe reads
- ctypes-based C library bindings
- Combining libmagic flag options
Use cases
- Detecting upload MIME types in web apps
- Validating files before processing pipelines
- Replacing shell file invocations from Python
- Inspecting buffers without writing temp files