如何在python中找到文件的mime类型? [英] How to find the mime type of a file in python?

查看:354
本文介绍了如何在python中找到文件的mime类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

假设:浏览器通过HTTP响应中的mime-type(内容类型?)标头确定要使用哪个应用程序/查看器.

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

基于此假设,除了文件的字节外,您还希望保存MIME类型.

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

您将如何找到文件的MIME类型?我目前在Mac上,但是在Windows上也应该可以使用.

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

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

Does the browser add this information when posting the file to the web page?

是否存在用于查找此信息的整洁的python库? WebService还是(甚至更好的)可下载数据库?

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

推荐答案

toivotuo建议的python-magic方法已过时. Python魔术的当前主干位于Github上,并根据那里的自述文件找到MIME类型,就是这样.

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'

这篇关于如何在python中找到文件的mime类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆