Get file MIME type in Python

You can get file mime type in python by using python-magic library. You can install python-magic using PIP.

$ pip install python-magic

To find mime type, import magic library and pass file path into magic.from_file()

>>> import magic
>>> magic.from_file("path/to/file.pdf", mime=True)
'application/pdf'

If you face error “AttributeError: ‘module’ object has no attribute ‘from_file’” , then here is work around for this.

>>> import magic
>>> m = magic.open(magic.MAGIC_MIME)
>>> m.load()
>>> m.file("path/to/file.pdf")
(Visited 481 times, 3 visits today)