Categories
Python Answers

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

Spread the love

Sometimes, we want to find the MIME type of a file in Python.

In this article, we’ll look at how to find the MIME type of a file in Python.

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

To find the MIME type of a file in Python, we can use the python-magic package.

To install it, we run:

pip install python-magic

Then we use it by writing:

import magic

mime = magic.Magic(mime=True)
t = mime.from_file("foo.csv")
print(t)

We invoke the Magic constructor with mime set to True to let us get the MIME type of the file.

Then we call mime.from_file with the path of the file to get the MIME type of to return the MIME type of the file as a string.

Therefore, t is something like 'text/plain'.

Conclusion

To find the MIME type of a file in Python, we can use the python-magic package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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