Ricky Wilson
Ricky Wilson

Reputation: 3359

How to predict the mime type of a file based on its name?

This function is used to predict the mime type of a file based on its name. If it fails to predict the mime type, it defaults to application/octet-stream, aka arbitrary binary. I would like to know if there is a more Pythonic / cleaner way of writing this function.

from mimetypes import guess_type

def guess_mime(fname):
    try:
        return tuple(guess_type(fname)[0].split('/'))
    except AttributeError:
        return 'application', 'octet-stream'

Upvotes: 1

Views: 362

Answers (2)

tobias_k
tobias_k

Reputation: 82949

I would not use a try/except in this case, since this is not really "exceptional" behavior, but just the case that guess_type returns None as a type. A plain old if/else or ternary ... if ... else ... would be more appropriate, making it clearer what the code is doing, and the latter is even shorter:

 def guess_mime(fname):
    _type, _ = mimetypes.guess_type(fname)
    return tuple(_type.split("/")) if _type is not None else "application/octet-stream"

You could also use or to use _type or a default if _type is "falsey".

 def guess_mime(fname):
    _type, _ = mimetypes.guess_type(fname)
    return tuple((_type or "application/octet-stream").split("/"))

Of course, in both cases, the conversion to tuple may not be needed if the function may also return a list.

Upvotes: 1

Aviv Yaniv
Aviv Yaniv

Reputation: 6298

Use the Magic library:

import magic
mime = magic.Magic(mime=True)
mime.from_file("testdata/test.pdf") # 'application/pdf'

Easy Install with:

pip install python-magic

Upvotes: 3

Related Questions