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

Introduction

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
print(mimetypes.MimeTypes().guess_type('my_file.txt')[0])

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)
mime.from_file("my_file.txt")