A Python wrapper for libmagic that identifies file types by checking their headers.
python-magic is a Python wrapper for the libmagic C library that identifies file types by examining file headers. It provides the same functionality as the Unix `file` command within Python applications, allowing developers to programmatically determine file formats and MIME types. The library solves the problem of reliable file type identification without relying on file extensions.
Python developers who need to identify file types programmatically in applications like file upload systems, content management tools, or security scanners. System administrators and DevOps engineers who want to integrate file identification into Python-based automation scripts.
Developers choose python-magic because it provides a battle-tested interface to the industry-standard libmagic library, offering more reliable file identification than simple extension checking. Its thin wrapper approach ensures minimal overhead while maintaining compatibility with libmagic's extensive file type database.
A python wrapper for libmagic
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.
Leverages libmagic's comprehensive database, providing the same reliable file identification as the Unix 'file' command, which is battle-tested for various formats.
Returns standard MIME types with the mime=True flag, making it ideal for web applications that need to handle file uploads with proper content-type headers, as shown in usage examples.
Can automatically uncompress and identify contents of files like gzip with the uncompress=True flag, adding depth to file analysis without extra steps, demonstrated in the README.
Offers easy-to-use functions like from_file and from_buffer for common file type detection, with clear examples that recommend reading at least 2048 bytes for accuracy.
Requires separate installation of libmagic C library, which can be complex on Windows and may fail with environment-specific issues like missing DLLs, as detailed in troubleshooting.
The Magic class is explicitly not thread-safe and unsafe for sharing across threads, limiting its use in multi-threaded applications without careful instance management.
Installation on Windows often requires manual DLL handling and can lead to errors like access violations with mixed builds, making deployment more cumbersome than pure-Python alternatives.