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?
You could try out : magic's mimetype
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With