Getting MIME Types on Files & Buffers in Python

Through programming languages I’ve been through, finding MIME types is not that kinda easy, the language might not have a built-in function for that or if they have it won’t be that efficient, I can recall in PHP I’d activated the finfo module to find MIME type of existing files.

Now in Python, we have a built-in module with is the mimetypes but isn’t that efficient because last time I used it to find a MIME type of a .html file; I couldn’t get an accurate result, below is a simple function I use to get MIME type of a file in python

import mimetypes, os
def getMIME( File ):
	mimes = mimetypes.read_mime_types( File )
	filename, ext = os.path.splitext( File )
	if bool( mimes ) is False:
		return False
		for i in mimes.items():
			if i[ 0 ] == ext:
				return i[ 1 ]
print( getMIME( '/var/www/html/index.html' ) )

But that couldn’t give me an efficient result, no result for the .html file. I went into search (Google & StackOverflow…LOL) and found the magic module, this module is not installed by default in Python so firstly we’ll get this module. If you are using PIP then just

pip install magic

or normal through the OS repository

$ sudo apt-get install python-magic

Rewriting the function above with the magic module:

import magic
def getMIME( File ):
	f = magic.MAGIC_MIME )
		return f.file( File )

print( getMIME( '/var/www/html/index.html' ) )

You should see that the above magic module looks accurate and efficient, this module also accepts the buffer method using

f.buffer('My simple string')

and this also returns the accurate MIME. Actually am feeling sleepy typing this but what I typed is working. Cheers 🙂