13 year later...
Most of the answers for python 3 on this page are either outdated or incomplete.
To get the mime type of a file on python3 I normally use:
import mimetypes
mt = mimetypes.guess_type("file.ext")[0]
From Python docs:
mimetypes.guess_type
(url, strict=True)
Guess the type of a file based on its filename, path or URL, given by url. URL can be a string or a path-like object.
The return value is a tuple (type, encoding)
where type is None
if the type can’t be guessed (missing or unknown suffix) or a string of the form 'type/subtype'
, usable for a MIME content-type header.
encoding is None
for no encoding or the name of the program used to encode (e.g. compress or gzip). The encoding is suitable for use as a Content-Encoding header, not as a Content-Transfer-Encoding header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively.
The optional strict argument is a flag specifying whether the list of known MIME types is limited to only the official types registered with IANA. When strict is True
(the default), only the IANA types are supported; when strict is False
, some additional non-standard but commonly used MIME types are also recognized.
Changed in version 3.8: Added support for url being a path-like object.