1 min read

Python Mimetypes Module

The mimetypes module converts between a filename or URL and the MIME type associated with the filename extension. It provides functions to guess the type of a file based on its name or URL, and to guess the extension based on a MIME type.

Importing the Module

import mimetypes

Guessing MIME Types

The mimetypes.guess_type() function guesses the type of a file based on its filename or URL. It returns a tuple (type, encoding).

import mimetypes

filename = 'example.html'
mime_type, encoding = mimetypes.guess_type(filename)

print(f"MIME type: {mime_type}")   # Output: text/html
print(f"Encoding: {encoding}")     # Output: None

If the file is compressed, the encoding will be returned.

filename = 'example.tar.gz'
mime_type, encoding = mimetypes.guess_type(filename)

print(f"MIME type: {mime_type}")   # Output: application/x-tar
print(f"Encoding: {encoding}")     # Output: gzip

Guessing Extensions

The mimetypes.guess_extension() function guesses the extension for a file based on its MIME type.

import mimetypes

extension = mimetypes.guess_extension('text/html')
print(extension) # Output: .html

extension = mimetypes.guess_extension('application/json')
print(extension) # Output: .json

Adding Custom Types

You can add your own types to the mapping using add_type().

mimetypes.add_type('application/x-my-app', '.myapp')
print(mimetypes.guess_type('file.myapp'))

programming/python/python