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 magic library.

To install it, we run

pip install python-magic

We also have to install a few packages in the OS the script is running on.

In Ubuntu like distros we run

sudo apt-get install libmagic1

And on Windows, we run

pip install python-magic-bin

On OS X, we run brew install libmagic with Homebrew or port install file with macports.

Then we use it by writing

import magic

mime = magic.Magic(mime=True)
mime_type = mime.from_file("testdata/test.pdf")

to create a Magic object.

Then we call from_file on it with the path to our file to return its MIME type.

Conclusion

To find the mime type of a file in Python, we can use the magic library.

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 *