The Python Oracle

How to find the mime type of a file in python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Bleepage Open

--

Chapters
00:00 Question
01:01 Accepted answer (Score 281)
01:24 Answer 2 (Score 122)
01:53 Answer 3 (Score 53)
02:19 Answer 4 (Score 53)
02:44 Thank you

--

Full question
https://stackoverflow.com/questions/4358...

Accepted answer links:
[toivotuo]: https://stackoverflow.com/a/2133843/5337...
[Python-magic's]: http://github.com/ahupp/python-magic

Answer 2 links:
[mimetypes module]: https://docs.python.org/library/mimetype...
[UploadedFile]: https://docs.djangoproject.com/en/dev/to...

Answer 3 links:
[Old Post]: https://stackoverflow.com/a/14412233/118...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #mime

#avk47



ACCEPTED ANSWER

Score 311


The python-magic method suggested by toivotuo is outdated. Python-magic's current trunk is at Github and based on the readme there, finding the MIME-type, is done like this.

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



ANSWER 2

Score 128


The mimetypes module in the standard library will determine/guess the MIME type from a file extension.

If users are uploading files the HTTP post will contain the MIME type of the file alongside the data. For example, Django makes this data available as an attribute of the UploadedFile object.




ANSWER 3

Score 60


This seems to be very easy

>>> from mimetypes import MimeTypes
>>> import urllib 
>>> mime = MimeTypes()
>>> url = urllib.pathname2url('Upload.xml')
>>> mime_type = mime.guess_type(url)
>>> print mime_type
('application/xml', None)

Please refer Old Post

Update - In python 3+ version, it's more convenient now:

import mimetypes
print(mimetypes.guess_type("sample.html"))



ANSWER 4

Score 56


More reliable way than to use the mimetypes library would be to use the python-magic package.

import magic
m = magic.open(magic.MAGIC_MIME)
m.load()
m.file("/tmp/document.pdf")

This would be equivalent to using file(1).

On Django one could also make sure that the MIME type matches that of UploadedFile.content_type.