mimetypes
The Python mimetypes
module provides tools to map filenames to MIME types and vice versa. It’s useful for determining the type of data a file contains based on its filename extension.
Here’s an example:
>>> import mimetypes
>>> mimetypes.guess_type("example.txt")
('text/plain', None)
Key Features
- Maps file extensions to MIME types
- Supports both standard and custom MIME types
- Provides functions to guess MIME types and extensions
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
mimetypes.guess_type() |
Function | Guesses the MIME type of a file based on its filename |
mimetypes.guess_extension() |
Function | Guesses the file extension for a given MIME type |
mimetypes.add_type() |
Function | Adds a mapping between a MIME type and extension |
Examples
Guessing the MIME type of a file:
>>> import mimetypes
>>> mimetypes.guess_type("document.pdf")
('application/pdf', None)
Guessing the file extension for a MIME type:
>>> mimetypes.guess_extension("image/jpeg")
'.jpg'
Adding a custom MIME type:
>>> mimetypes.add_type("application/x-custom_app", ".ca")
>>> mimetypes.guess_type("file.ca")
('application/x-custom_app', None)
Common Use Cases
- Determining the MIME type of files for HTTP responses
- Associating file extensions with MIME types in web applications
- Extending MIME type support with custom types and extensions
Real-World Example
Suppose you’re building a web application and need to determine the MIME type of uploaded files to process them correctly. Here’s how you can use the mimetypes
module:
>>> import mimetypes
>>> def get_file_mime_type(filename):
... mime_type, _ = mimetypes.guess_type(filename)
... return mime_type or "application/octet-stream"
...
>>> get_file_mime_type("upload.docx")
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
This code snippet helps identify the MIME type of an uploaded file, ensuring the web application processes it appropriately based on its content type.
Related Resources
Tutorial
Sending Emails With Python
In this tutorial, you'll learn how to send emails using Python. Find out how to send plain-text and HTML messages, add files as attachments, and send personalized emails to multiple people.
For additional information on related topics, take a look at the following resources:
- Get Started With Django User Management (Tutorial)
- Sending Emails Using Python (Course)
- Building a Django User Management System (Course)
By Leodanis Pozo Ramos • Updated July 15, 2025