Better, more accurate mime type detection in Python

The Python mimetypes module is not particularly accurate and bases its results on a file extension. The only way to get a more accurate result is to invoke the Unix command fileusing the subprocess.Popenfollowing:

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

It feels inelegant. Is there a better way to do this without naming file, but still achieving the same level of accuracy?

+5
source share
2 answers
+7
source

I use something similar, but in a little shorthand:

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

It may not be more elegant, but it is shorter and a little easier to read, and I always prefer it.

+2
source

All Articles