Find the Mime Type of a File in Python
Last Updated :
24 Apr, 2025
Determining the MIME (Multipurpose Internet Mail Extensions) type of a file is essential when working with various file formats. Python provides several libraries and methods to efficiently check the MIME type of a file. In this article, we'll explore different approaches to find the mime type of a file in Python.
Mime Type of a File in Python
Below are some of the ways by which we can find the mime type of a file in Python:
- Using the mimetypes module
- Using the python-magic Library
- Using the imghdr Module
- Using the os Module
Using the mimetypes Module
In this example, the Python code utilizes the mimetypes
module to determine the MIME type of the file 'output.txt' using the guess_type
function. The resulting MIME type is then printed to the console.
Python3
import mimetypes
# Get MIME type using guess_type
file_path = 'output.txt'
mime_type, encoding = mimetypes.guess_type(file_path)
print("MIME Type:", mime_type)
Output:

Using the Python-Magic Library
In this example, the Python code employs the python-magic
library to create a magic
object, allowing the determination of the MIME type for the file 'output.txt' using the from_file
method. The resulting MIME type is then printed to the console.
Python3
import magic
# Create a magic object
mime = magic.Magic()
# Get MIME type using from_file
file_path = 'output.txt'
mime_type = mime.from_file(file_path)
print(f'MIME Type: {mime_type}')
Output:

Using the imghdr Module for Images
The imghdr
module is specifically used for determining the MIME type of images.The what
function returns the MIME type of the specified image file. In the above code On passing the image path to the what() method, It returned the mime type of the image file
Python3
import imghdr
# Get MIME type for images using what
image_path = 'image005.png'
mime_type = imghdr.what(image_path)
print(f'MIME Type: {mime_type}')