假设您想要在某个地方保存一堆文件,例如在blob中。假设您希望通过网页分发这些文件,并让客户端自动打开正确的应用程序/查看器。

假设:浏览器通过HTTP响应中的mime-type (content-type?)报头确定要使用哪个应用程序/查看器。

基于这个假设,除了文件的字节外,还需要保存MIME类型。

如何找到文件的MIME类型?我现在用的是Mac,但这应该也适用于Windows。

浏览器是否在将文件发布到网页时添加此信息?

是否有一个简洁的python库来查找这些信息?WebService还是(更好的)一个可下载的数据库?


当前回答

@toivotuo的方法在python3下工作得最好,最可靠。我的目标是识别那些没有可靠的.gz扩展名的gzip文件。我安装了python3-magic。

import magic

filename = "./datasets/test"

def file_mime_type(filename):
    m = magic.open(magic.MAGIC_MIME)
    m.load()
    return(m.file(filename))

print(file_mime_type(filename))

对于一个gzip文件,它返回: 应用程序/ gzip;charset =二进制

对于解压缩的TXT文件(iostat数据): 文本/平原;charset = us - ascii

对于tar文件: 应用程序/ x-tar;charset =二进制

对于bz2文件: 应用程序/ x-bzip2;charset =二进制

最后但并非最不重要的一个。zip文件: 应用程序/邮政编码;charset =二进制

其他回答

这似乎很简单

>>> 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)

请参阅旧帖

更新-在python 3+版本中,现在更方便了:

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

toivotuo提出的蟒蛇魔法方法已经过时了。Python-magic当前的主干在Github,基于那里的自述me,找到mime类型,是这样做的。

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

Python 3参考:https://docs.python.org/3.2/library/mimetypes.html

mimetypes.guess_type(url, strict=True) Guess the type of a file based on its filename or URL, given by url. The return value is a tuple (type, encoding) where type is None if the type can’t be guessed (missing or unknown suffix) or a string of the form 'type/subtype', usable for a MIME content-type header. encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The encoding is suitable for use as a Content-Encoding header, not as a Content-Transfer-Encoding header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively. The optional strict argument is a flag specifying whether the list of known MIME types is limited to only the official types registered with IANA. When strict is True (the default), only the IANA types are supported; when strict is False, some additional non-standard but commonly used MIME types are also recognized.

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

有3个不同的库包装libmagic。

其中2个在pypi上可用(所以PIP安装可以工作):

filemagic python-magic

另一种类似于python-magic的方法可以在最新的libmagic源代码中直接获得,它可能是您的linux发行版中所拥有的。

在Debian中,python-magic包就是这样的,它像toivotuo说的那样被使用,它并没有像Simon Zimmermann说的那样被淘汰(IMHO)。

在我看来,这是另一种说法(出自《libmagic》的原作者)。

太糟糕了,pypi上不能直接使用。

标准库中的mimetypes模块将根据文件扩展名确定/猜测MIME类型。

如果用户正在上传文件,HTTP post将在数据旁边包含文件的MIME类型。例如,Django将此数据作为UploadedFile对象的属性提供。