How to find the mime type of a file in Python

media type (also known as a Multipurpose Internet Mail Extensions or MIME type) is a standard that indicates the nature and format of a document, file, or assortment of bytes. It is defined and standardized in IETF’s RFC 6838.

The screenshot showing a list of MIME types. Image courtesy of https://jhierrot.github.io/openprodoc/help/EN/ListMimeTypes.html

Python has a module called mimetypes that you can use to guess the mime type of a file. However, it is not a reliable way to know the mime type of a file. For example,

>>> import mimetypes
>>> print(mimetypes.MimeTypes().guess_type('my_file.txt')[0])
text/plain

You can also use a non-standard module called python-magic to deduce the mimetype of a file. For example,

>>> import magic
>>> mime = magic.Magic(mime=True)
>>> mime.from_file("my_file.txt")
text/plain

See how to detect mime type of a file in Java using Apache Tika library.

Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via nguyenvungoctung@gmail.com if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.

https://www.itersdesktop.com/author/nvntung/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.