Find the mime type of a file in Python


Python tip:

You can use mimetypes.guess_type to get a mime type and encoding for a file from its name.

For example👇

import mimetypes

mime_type, _ = mimetypes.guess_type("my _ file. pdf")
print(mime_type)
# => application/pdf

mime_type, encoding = mimetypes.guess_type("archive. tar.gz")
print(mime_type, encoding)
# => application/x-tar gzip