How to find the mime type of a file in Python?



Using python standard library

Python comes with a module called mime types that can be used to guess the mime type of a filename. The only problem with this library is that it does guess using the filename and not by the contents:

import mimetypes

The previous code will print text/plain.

Guess mime type with python using file contents

You can use the package pyhon-magic to guess the mime type using the file contents. First, install the library with:

pip install python-magic

Then you can use it like this example:

import magic
mime = magic.Magic(mime=True)