Fork me on GitHub

The filemagic API

Importing the magic module provides access to all filemagic primitives. Most importantly the Magic class.


If something goes with libmagic, an exception will be raised.

exception magic.api.MagicError(errno, error)[source]

errno is the numerical error code returned by libmagic. error is the textual description of that error code, as supplied by libmagic.

MagicError inherits from EnvironmentError.


The Magic class supports context managers, meaning it can be used with the with statement. Using the with statement is the recommended usage as failing to call close() will leak resources. See Usage for guidance.

class magic.Magic([paths, flags])

Instances of this class provide access to libmagics‘s file identification capabilities. Multiple instances may exist, each instance is independant from the others.

To supply a custom list of magic database files instead of letting libmagic search the default paths, supply a list of filenames using the paths argument. These filenames may be unicode string as described in Memory management.

By default flags is magic.MAGIC_MIME_TYPE which requests default behaviour from libmagic. This behaviour can be controlled by passing alternative Constants for flags.


Identify a file from a given filename. The file will be opened by libmagic, reading sufficient contents to complete the identification.


Identify a file from the contents of a string or buffer.


Release any resources held by libmagic. This will be called automatically when a context manager exists.


Prints a list of magic entries to standard out. There is no return value. It’s mostly intended for debugging.


This property will be True if the magic database files loaded by libmagic are consistent.

This class encapsulates the low level ctypes api from magic.api that interfaces directly with libmagic. It’s not expected that the user would want to do this.

If you do not know if libmagic is available, refer to the Installation section of the guide.



Default flag for magic.Magic that requests default behaviour from libmagic.


Supply to magic.Magic constructor to return mime type instead of textual description.


Supply to magic.Magic constructor to return mime encoding instead of textual description.