为什么 mimetypes.guess_type('a.json') 在 centos 7 中不工作

why is mimetypes.guess_type('a.json') not working in centos 7

在 Centos 中,为什么 python 2.7 预构建库 mimetypes.guess_type 不返回 json 文件的 mimetype? https://docs.python.org/2/library/mimetypes.html#

我在 mimetypes 中使用 guess_type,它在 centos/ubuntu 中使用 returns 不同的值。 pythonic 从不同 OS 中的文件名推断出 mimetype 的方法是什么?

在 ubuntu 14.04 中,returns 正确的 mime 类型

>>> import mimetypes
>>> mimetypes.guess_type('a.json')
('application/json', None)

但在Centos7中

>>> import mimetypes
>>> mimetypes.guess_type('a.json')
(None, None)
>>> mimetypes.guess_type('a.JSON')
(None, None)

我检查了类似的问题和建议的答案,它只有在给定内容的文件存在时才有效... How to find the mime type of a file in python?

在 CentOS 7 上,您需要安装一个名为 "mailcap":

的软件包
yum search mailcap

这被描述为 "Helper application and MIME type associations for file types"。

安装 mailcap 后,以下将起作用:

>>> import mimetypes
>>> mimetypes.guess_type('a.json')
('application/json', None)

(A not-so-related 回答)在 Windows 上,从注册表中读取 Mime 类型,因此您可以通过编辑注册表项手动添加 mime 类型。

就我而言,我开发了一个 python 应用程序来接收电子表格(.xls.xlsx)。它在我的开发计算机 (Windows 10/11) 上运行,但在生产服务器 (Windows Server 2008) 上,无法识别 .xlsx 文件。 mimetypes.guess_type(someXLSXfile.url) 打印了 None.

所以我查看了服务器的注册表,结果发现它太旧了,没有.xlsx条目。所以我手动添加了它。 (将下面的代码保存为xlsx.reg和运行它在Windows,然后可以添加条目。)

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.xlsx]
@="ET.Xlsx.6"
"Content Type"="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
"PerceivedType"="document"

如果您碰巧知道缺少的内容类型,您可以通过这种方式修复它。在代码中,您应该将方括号中的 .xlsx 更改为您想要的扩展名,对于以下值,您可以从已知计算机上复制它们。