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.
pip install libmagicVerified import paths — ran on the pinned version, not inferred.
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.
Before `pip install libmagic`, ensure the C library is present. For Debian/Ubuntu: `sudo apt-get install libmagic1`. For macOS (Homebrew): `brew install libmagic`. For Fedora/RHEL: `sudo dnf install file-libs`.
Always verify that the path provided to `from_file()` points to an actual file, for example, by using `os.path.isfile(path)`.
You may need to set the `MAGIC_FILE` environment variable to the full path of `magic.mgc` (the database file) or `LIBMAGIC_PATH` to the shared library (`libmagic.so`, `libmagic.dylib`, `libmagic.dll`) before running your Python script.
While `libmagic` itself handles various encodings, the Python bindings typically return Unicode strings. If parsing output, be aware of character sets. For MIME types, specify `mime=True` in the `Magic` constructor.
No dependency data recorded yet.