Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better, more accurate mime type detection in Python

Python's mimetypes module isn't especially accurate and bases its results on the file extension. The only way I can think of to get a more accurate result is to call the Unix file command with subprocess.Popen as so:

import subprocess
mimetype = subprocess.Popen(['file', '/path/to/file', '--mime-type', '-b'], 
    stdout=subprocess.PIPE).stdout.read().strip()

This feels inelegant. Is there a better way to do this without having to call file but still achieving the same level of accuracy?

like image 747
Matty Avatar asked Apr 21 '12 22:04

Matty


2 Answers

You could try out : magic's mimetype

like image 96
Mads Avatar answered Sep 23 '22 20:09

Mads


I use something similar but slightly abbreviated:

import subprocess
mimeType = subprocess.check_output(['file', '-ib', '/path/to/file']).strip()

It may not be more elegant, but it's shorter and a bit easier to read, and I always prefer that.

like image 37
mwsikora Avatar answered Sep 22 '22 20:09

mwsikora