Find the MIME Type of a File in Python



In some scenarios, it is important to determine the MIME type of a file to verify its content type, especially when working with file uploads or handling media files.

Python provides modules such as mimetypes and magic to determine the MIME type of a file. In this article, we'll explore different methods to find a file's MIME type using Python.

Using mimetypes.guess_type()

The mimetypes module in Python provides the guess_type() function, which is used to guess the MIME type and to encode of a file based on its filename or URL.

Example

In this example, we are using the mimetypes.guess_type() function to get the MIME type of the given file:

import mimetypes

filename = "example.pdf"
mime_type, encoding = mimetypes.guess_type(filename)

print(mime_type)  # Output: application/pdf

Here is the output of the above program ?

application/pdf

Using Python-Magic library

The python-magic library uses libmagic to determine the MIME type by examining the file content itself, which makes it more accurate than just guessing from the file extension.

Example

Below is an example using Python-Magic to find the MIME type of a file based on its content ?

import magic

file_path = "example.png"
mime = magic.Magic(mime=True)
mime_type = mime.from_file(file_path)

print(mime_type)  # Output: image/png

Following is the output of the above program ?

image/png

Note: We need to install python-magic using pip install python-magic and it may require additional system packages like libmagic on Linux or macOS.

Updated on: 2025-05-15T15:48:28+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements