<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p>

<p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p>

<p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p>

<p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p>

<p>Does the browser add this information when posting the file to the web page?</p>

<p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>

[{'answer_id': 43588, 'author': 'David Webb', 'author_id': 3171, 'author_profile': 'https://Stackoverflow.com/users/3171', 'pm_score': 7, 'selected': False, 'text': '<p>The <a href="https://docs.python.org/library/mimetypes.html" rel="noreferrer">mimetypes module</a> in the standard library will determine/guess the MIME type from a file extension.</p>\n\n<p>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 <a href="https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploadedfile-objects" rel="noreferrer">UploadedFile</a> object.</p>\n'}, {'answer_id': 43616, 'author': 'akdom', 'author_id': 145, 'author_profile': 'https://Stackoverflow.com/users/145', 'pm_score': 3, 'selected': False, 'text': '<p>You didn\'t state what web server you were using, but Apache has a nice little module called <a href="http://httpd.apache.org/docs/1.3/mod/mod_mime_magic.html" rel="nofollow noreferrer">Mime Magic</a> which it uses to determine the type of a file when told to do so.  It reads some of the file\'s content and tries to figure out what type it is based on the characters found.  And as <a href="https://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python#43588">Dave Webb Mentioned</a> the <a href="http://docs.python.org/lib/module-mimetypes.html" rel="nofollow noreferrer">MimeTypes Module</a> under python will work, provided an extension is handy.</p>\n\n<p>Alternatively, if you are sitting on a UNIX box you can use <code>sys.popen(\'file -i \' + fileName, mode=\'r\')</code> to grab the MIME type.  Windows should have an equivalent command, but I\'m unsure as to what it is. </p>\n'}, {'answer_id': 1662074, 'author': 'apito', 'author_id': 180008, 'author_profile': 'https://Stackoverflow.com/users/180008', 'pm_score': 3, 'selected': False, 'text': '<p>in python 2.6:</p>\n<pre><code>import shlex\nimport subprocess\nmime = subprocess.Popen(&quot;/usr/bin/file --mime &quot; + shlex.quote(PATH), shell=True, \\\n    stdout=subprocess.PIPE).communicate()[0]\n</code></pre>\n'}, {'answer_id': 2133843, 'author': 'toivotuo', 'author_id': 223251, 'author_profile': 'https://Stackoverflow.com/users/223251', 'pm_score': 6, 'selected': False, 'text': '<p>More reliable way than to use the mimetypes library would be to use the python-magic package.</p>\n\n<pre><code>import magic\nm = magic.open(magic.MAGIC_MIME)\nm.load()\nm.file("/tmp/document.pdf")\n</code></pre>\n\n<p>This would be equivalent to using file(1).</p>\n\n<p>On Django one could also make sure that the MIME type matches that of UploadedFile.content_type.</p>\n'}, {'answer_id': 2753385, 'author': 'Simon Zimmermann', 'author_id': 230264, 'author_profile': 'https://Stackoverflow.com/users/230264', 'pm_score': 9, 'selected': True, 'text': '<p>The python-magic method suggested by <a href="https://stackoverflow.com/a/2133843/5337834">toivotuo</a> is outdated. <a href="http://github.com/ahupp/python-magic" rel="noreferrer">Python-magic\'s</a> current trunk is at Github and based on the readme there, finding the MIME-type, is done like this.</p>\n<pre><code># For MIME types\nimport magic\nmime = magic.Magic(mime=True)\nmime.from_file(&quot;testdata/test.pdf&quot;) # \'application/pdf\'\n</code></pre>\n'}, {'answer_id': 11101343, 'author': 'Helder', 'author_id': 998341, 'author_profile': 'https://Stackoverflow.com/users/998341', 'pm_score': 2, 'selected': False, 'text': '<p>The mimetypes module just recognise an file type based on file extension. If you will try to recover a file type of a file without extension, the mimetypes will not works.</p>\n'}, {'answer_id': 12297929, 'author': 'mammadori', 'author_id': 959278, 'author_profile': 'https://Stackoverflow.com/users/959278', 'pm_score': 4, 'selected': False, 'text': '<p>There are 3 different libraries that wraps libmagic.</p>\n\n<p>2 of them are available on pypi (so pip install will work):</p>\n\n<ul>\n<li>filemagic</li>\n<li>python-magic</li>\n</ul>\n\n<p>And another, similar to python-magic is available directly in the latest libmagic sources, and it is the one you probably have in your linux distribution.</p>\n\n<p>In Debian the package python-magic is about this one and it is used as toivotuo said and it is not obsoleted as Simon Zimmermann said (IMHO).</p>\n\n<p>It seems to me another take (by the original author of libmagic).</p>\n\n<p>Too bad is not available directly on pypi.</p>\n'}, {'answer_id': 21755201, 'author': 'Laxmikant Ratnaparkhi', 'author_id': 1182058, 'author_profile': 'https://Stackoverflow.com/users/1182058', 'pm_score': 6, 'selected': False, 'text': '<p>This seems to be very easy</p>\n<pre><code>&gt;&gt;&gt; from mimetypes import MimeTypes\n&gt;&gt;&gt; import urllib \n&gt;&gt;&gt; mime = MimeTypes()\n&gt;&gt;&gt; url = urllib.pathname2url(\'Upload.xml\')\n&gt;&gt;&gt; mime_type = mime.guess_type(url)\n&gt;&gt;&gt; print mime_type\n(\'application/xml\', None)\n</code></pre>\n<p>Please refer <a href="https://stackoverflow.com/a/14412233/1182058">Old Post</a></p>\n<p><strong>Update</strong> - In python 3+ version, it\'s more convenient now:</p>\n<pre><code>import mimetypes\nprint(mimetypes.guess_type(&quot;sample.html&quot;))\n</code></pre>\n'}, {'answer_id': 28306825, 'author': 'ewr2san', 'author_id': 2883775, 'author_profile': 'https://Stackoverflow.com/users/2883775', 'pm_score': 3, 'selected': False, 'text': '<p>@toivotuo \'s method worked best and most reliably for me under python3.  My goal was to identify gzipped files which do not have a reliable .gz extension. I installed python3-magic.</p>\n\n<pre><code>import magic\n\nfilename = "./datasets/test"\n\ndef file_mime_type(filename):\n    m = magic.open(magic.MAGIC_MIME)\n    m.load()\n    return(m.file(filename))\n\nprint(file_mime_type(filename))\n</code></pre>\n\n<p>for a gzipped file it returns:\napplication/gzip; charset=binary</p>\n\n<p>for an unzipped txt file (iostat data):\ntext/plain; charset=us-ascii</p>\n\n<p>for a tar file:\napplication/x-tar; charset=binary</p>\n\n<p>for a bz2 file: \napplication/x-bzip2; charset=binary</p>\n\n<p>and last but not least for me a .zip file: \napplication/zip; charset=binary</p>\n'}, {'answer_id': 39356849, 'author': 'Claude COULOMBE', 'author_id': 1209842, 'author_profile': 'https://Stackoverflow.com/users/1209842', 'pm_score': 3, 'selected': False, 'text': '<p>In Python 3.x and webapp with url to the file which couldn\'t have an extension or a fake extension. You should install python-magic, using </p>\n\n<pre><code>pip3 install python-magic\n</code></pre>\n\n<p>For Mac OS X, you should also install libmagic using</p>\n\n<pre><code>brew install libmagic\n</code></pre>\n\n<p>Code snippet</p>\n\n<pre><code>import urllib\nimport magic\nfrom urllib.request import urlopen\n\nurl = "http://...url to the file ..."\nrequest = urllib.request.Request(url)\nresponse = urlopen(request)\nmime_type = magic.from_buffer(response.readline())\nprint(mime_type)\n</code></pre>\n\n<p>alternatively you could put a size into the read</p>\n\n<pre><code>import urllib\nimport magic\nfrom urllib.request import urlopen\n\nurl = "http://...url to the file ..."\nrequest = urllib.request.Request(url)\nresponse = urlopen(request)\nmime_type = magic.from_buffer(response.read(128))\nprint(mime_type)\n</code></pre>\n'}, {'answer_id': 45770476, 'author': 'Artem Bernatskyi', 'author_id': 5751147, 'author_profile': 'https://Stackoverflow.com/users/5751147', 'pm_score': 0, 'selected': False, 'text': '<p>I \'ve tried a lot of examples but with Django <a href="http://mutagen.readthedocs.io" rel="nofollow noreferrer">mutagen</a> plays nicely.  </p>\n\n<p>Example checking if files is <code>mp3</code>  </p>\n\n<pre><code>from mutagen.mp3 import MP3, HeaderNotFoundError  \n\ntry:\n    audio = MP3(file)\nexcept HeaderNotFoundError:\n    raise ValidationError(\'This file should be mp3\')\n</code></pre>\n\n<p>The downside is that your ability to check file types is limited, but it\'s a great way if you want not only check for file type but also to access additional information.</p>\n'}, {'answer_id': 46758932, 'author': 'Gringo Suave', 'author_id': 450917, 'author_profile': 'https://Stackoverflow.com/users/450917', 'pm_score': 4, 'selected': False, 'text': "<p><strong>2017 Update</strong></p>\n\n<p>No need to go to github, it is on PyPi under a different name:</p>\n\n<pre><code>pip3 install --user python-magic\n# or:\nsudo apt install python3-magic  # Ubuntu distro package\n</code></pre>\n\n<p>The code can be simplified as well:</p>\n\n<pre><code>&gt;&gt;&gt; import magic\n\n&gt;&gt;&gt; magic.from_file('/tmp/img_3304.jpg', mime=True)\n'image/jpeg'\n</code></pre>\n"}, {'answer_id': 50985903, 'author': 'bodo', 'author_id': 1534459, 'author_profile': 'https://Stackoverflow.com/users/1534459', 'pm_score': 4, 'selected': False, 'text': '<h1>Python bindings to libmagic</h1>\n\n<p>All the different answers on this topic are very confusing, so I’m hoping to give a bit more clarity with this overview of the different bindings of libmagic. Previously mammadori gave a <a href="https://stackoverflow.com/a/2753385/1534459">short answer</a> listing the available option.</p>\n\n<h2>libmagic</h2>\n\n<ul>\n<li>module name: <code>magic</code></li>\n<li>pypi: <a href="https://pypi.org/project/file-magic/" rel="noreferrer">file-magic</a></li>\n<li>source: <a href="https://github.com/file/file/tree/master/python" rel="noreferrer">https://github.com/file/file/tree/master/python</a></li>\n</ul>\n\n<p>When determining a files mime-type, the tool of choice is simply called <code>file</code> and its back-end is called <code>libmagic</code>. (See the <a href="http://www.darwinsys.com/file/" rel="noreferrer">Project home page</a>.) The project is developed in a private cvs-repository, but there is a <a href="https://github.com/file/file" rel="noreferrer">read-only git mirror on github</a>.</p>\n\n<p>Now this tool, which you will need if you want to use any of the libmagic bindings with python, already comes with its own python bindings called <a href="https://pypi.org/project/file-magic/" rel="noreferrer"><code>file-magic</code></a>. There is not much dedicated documentation for them, but you can always have a look at the man page of the c-library: <a href="http://man7.org/linux/man-pages/man3/libmagic.3.html" rel="noreferrer"><code>man libmagic</code></a>. The basic usage is described in the <a href="https://github.com/file/file/tree/master/python" rel="noreferrer">readme file</a>:</p>\n\n<pre><code>import magic\n\ndetected = magic.detect_from_filename(\'magic.py\')\nprint \'Detected MIME type: {}\'.format(detected.mime_type)\nprint \'Detected encoding: {}\'.format(detected.encoding)\nprint \'Detected file type name: {}\'.format(detected.name)\n</code></pre>\n\n<p>Apart from this, you can also use the library by creating a <code>Magic</code> object using <code>magic.open(flags)</code> as shown in the <a href="https://github.com/file/file/tree/master/python/example.py" rel="noreferrer">example file</a>.</p>\n\n<p>Both <a href="https://stackoverflow.com/a/2133843/1534459">toivotuo</a> and ewr2san use these <code>file-magic</code> bindings included in the <code>file</code> tool. They mistakenly assume, they are using the <code>python-magic</code> package. <em>This seems to indicate, that if both <code>file</code> and <code>python-magic</code> are installed, the python module <code>magic</code> refers to the former one.</em></p>\n\n<h2>python-magic</h2>\n\n<ul>\n<li>module name: <code>magic</code></li>\n<li>pypi: <a href="https://pypi.org/project/python-magic/" rel="noreferrer">python-magic</a></li>\n<li>source: <a href="https://github.com/ahupp/python-magic" rel="noreferrer">https://github.com/ahupp/python-magic</a></li>\n</ul>\n\n<p>This is the library that Simon Zimmermann talks about in <a href="https://stackoverflow.com/a/2753385/1534459">his answer</a> and which is also employed by <a href="https://stackoverflow.com/a/2753385/1534459">Claude COULOMBE</a> as well as <a href="https://stackoverflow.com/a/46758932/1534459">Gringo Suave</a>.</p>\n\n<h2>filemagic</h2>\n\n<ul>\n<li>module name: <code>magic</code></li>\n<li>pypi: <a href="https://pypi.org/project/filemagic/" rel="noreferrer">filemagic</a></li>\n<li>source: <a href="https://github.com/aliles/filemagic" rel="noreferrer">https://github.com/aliles/filemagic</a></li>\n</ul>\n\n<p><strong>Note</strong>: This project was last updated in 2013!</p>\n\n<p>Due to being based on the same c-api, this library has some similarity with <code>file-magic</code> included in <code>libmagic</code>. It is only mentioned by <a href="https://stackoverflow.com/a/2753385/1534459">mammadori</a> and no other answer employs it. </p>\n'}, {'answer_id': 51510950, 'author': 'Ajay', 'author_id': 6164697, 'author_profile': 'https://Stackoverflow.com/users/6164697', 'pm_score': 1, 'selected': False, 'text': '<p>For byte Array type data you can use \nmagic.from_buffer(_byte_array,mime=True)</p>\n'}, {'answer_id': 56248128, 'author': 'Jak Liao', 'author_id': 6016411, 'author_profile': 'https://Stackoverflow.com/users/6016411', 'pm_score': 2, 'selected': False, 'text': "<p>I try mimetypes library first. If it's not working, I use python-magic libary instead.</p>\n\n<pre><code>import mimetypes\ndef guess_type(filename, buffer=None):\nmimetype, encoding = mimetypes.guess_type(filename)\nif mimetype is None:\n    try:\n        import magic\n        if buffer:\n            mimetype = magic.from_buffer(buffer, mime=True)\n        else:\n            mimetype = magic.from_file(filename, mime=True)\n    except ImportError:\n        pass\nreturn mimetype\n</code></pre>\n"}, {'answer_id': 57941308, 'author': 'oetzi', 'author_id': 9241362, 'author_profile': 'https://Stackoverflow.com/users/9241362', 'pm_score': 3, 'selected': False, 'text': '<p>python 3 ref: <a href="https://docs.python.org/3.2/library/mimetypes.html" rel="noreferrer">https://docs.python.org/3.2/library/mimetypes.html</a></p>\n\n<blockquote>\n  <p>mimetypes.guess_type(url, strict=True) Guess the type of a file based\n  on its filename or URL, given by url. The return value is a tuple\n  (type, encoding) where type is None if the type can’t be guessed\n  (missing or unknown suffix) or a string of the form \'type/subtype\',\n  usable for a MIME content-type header.</p>\n  \n  <p>encoding is None for no encoding or the name of the program used to\n  encode (e.g. compress or gzip). The encoding is suitable for use as a\n  Content-Encoding header, not as a Content-Transfer-Encoding header.\n  The mappings are table driven. Encoding suffixes are case sensitive;\n  type suffixes are first tried case sensitively, then case\n  insensitively.</p>\n  \n  <p>The optional strict argument is a flag specifying whether the list of\n  known MIME types is limited to only the official types registered with\n  IANA. When strict is True (the default), only the IANA types are\n  supported; when strict is False, some additional non-standard but\n  commonly used MIME types are also recognized.</p>\n</blockquote>\n\n<pre><code>import mimetypes\nprint(mimetypes.guess_type("sample.html"))\n</code></pre>\n'}, {'answer_id': 62673207, 'author': 'Eric McLachlan', 'author_id': 4093278, 'author_profile': 'https://Stackoverflow.com/users/4093278', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m surprised that nobody has mentioned it but <a href="https://pypi.org/project/Pygments" rel="nofollow noreferrer">Pygments</a> is able to make an educated guess about the mime-type of, particularly, text documents.</p>\n<p>Pygments is actually a Python syntax highlighting library but is has a method that will make an educated guess about which of 500 supported document types your document is.\ni.e. c++ vs C# vs Python vs etc</p>\n<pre class="lang-py prettyprint-override"><code>import inspect\n\ndef _test(text: str):\n    from pygments.lexers import guess_lexer\n    lexer = guess_lexer(text)\n    mimetype = lexer.mimetypes[0] if lexer.mimetypes else None\n    print(mimetype)\n\nif __name__ == &quot;__main__&quot;:\n    # Set the text to the actual defintion of _test(...) above\n    text = inspect.getsource(_test)\n    print(\'Text:\')\n    print(text)\n    print()\n    print(\'Result:\')\n    _test(text)\n</code></pre>\n<p>Output:</p>\n<pre><code>Text:\ndef _test(text: str):\n    from pygments.lexers import guess_lexer\n    lexer = guess_lexer(text)\n    mimetype = lexer.mimetypes[0] if lexer.mimetypes else None\n    print(mimetype)\n\n\nResult:\ntext/x-python\n</code></pre>\n<p>Now, it\'s not perfect, but if you need to be able to tell which of 500 document formats are being used, this is pretty darn useful.</p>\n'}, {'answer_id': 66012377, 'author': 'Pedro Lobito', 'author_id': 797495, 'author_profile': 'https://Stackoverflow.com/users/797495', 'pm_score': 5, 'selected': False, 'text': '<p>13 year later...<br />\nMost of the answers on this page for python 3 were either outdated or incomplete.<br />\nTo get the mime type of a file I use:</p>\n<pre><code>import mimetypes\n\nmt = mimetypes.guess_type(&quot;https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf&quot;)\nif mt:\n    print(&quot;Mime Type:&quot;, mt[0])\nelse:\n    print(&quot;Cannot determine Mime Type&quot;)\n\n# Mime Type: application/pdf\n</code></pre>\n<hr />\n<p><a href="https://trinket.io/python3/1485835cd1" rel="noreferrer">Live Demo</a></p>\n<hr />\n<p>From <a href="https://docs.python.org/3/library/mimetypes.html#mimetypes.guess_type" rel="noreferrer">Python docs</a>:</p>\n<p><code>mimetypes.guess_type</code>(<em>url</em>, <em>strict=True</em>)<a href="https://docs.python.org/3/library/mimetypes.html#mimetypes.guess_type" rel="noreferrer" title="Permalink to this definition"></a></p>\n<p>Guess the type of a file based on its filename, path or URL, given by <em>url</em>. URL can be a string or a <a href="https://docs.python.org/3/glossary.html#term-path-like-object" rel="noreferrer">path-like object</a>.</p>\n<p>The return value is a tuple <code>(type, encoding)</code> where <em>type</em> is <code>None</code> if the type can’t be guessed (missing or unknown suffix) or a string of the form <code>\'type/subtype\'</code>, usable for a MIME <em>content-type</em> header.</p>\n<p><em>encoding</em> is <code>None</code> for no encoding or the name of the program used to encode (e.g. <strong>compress</strong> or <strong>gzip</strong>). The encoding is suitable for use as a <em>Content-Encoding</em> header, <strong>not</strong> as a <em>Content-Transfer-Encoding</em> header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively.</p>\n<p>The optional <em>strict</em> argument is a flag specifying whether the list of known MIME types is limited to only the official types <a href="https://www.iana.org/assignments/media-types/media-types.xhtml" rel="noreferrer">registered with IANA</a>. When <em>strict</em> is <code>True</code> (the default), only the IANA types are supported; when <em>strict</em> is <code>False</code>, some additional non-standard but commonly used MIME types are also recognized.</p>\n<p>Changed in version 3.8: Added support for url being a <a href="https://docs.python.org/3/glossary.html#term-path-like-object" rel="noreferrer">path-like object</a>.</p>\n'}]
['https://Stackoverflow.com/questions/43580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2260/']