Computer >> Computer tutorials >  >> Programming >> Python

How to find the mime type of a file in Python?


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

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. 

example

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