python - 使用 Python 获取文件的 mimetype

标签 python

我想确定一个 xml 文件的 mimetype,但我收到有关某些实例作为第一个参数的错误。我是 python 的新手,请帮忙。下面是我正在使用的代码及其抛出的错误。

from mimetypes import MimeTypes
import urllib 
FILENAME = 'Upload.xml'
url = urllib.pathname2url(FILENAME)
type = MimeTypes.guess_type(url)
print type

**ERROR :** Traceback (most recent call last):
File "/home/navi/Desktop/quicksort.py", line 20, in <module>
type = MimeTypes.guess_type(url)
TypeError: unbound method guess_type() must be called with MimeTypes instance as first argument (got str instance instead)

最佳答案

错误表明您必须初始化 MimeTypes 类:

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

虽然你可以跳过这个并直接使用 mimetypes.guess_type:

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

关于python - 使用 Python 获取文件的 mimetype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14412211/

相关文章:

python - 如何将对象添加到 "pygame.sprite.Group()"?

python - Flask-SQLAlchemy 多对多连接条件

python - 比较 Python 中不同数量的列表

python - 在 Faker python 中使用名字和姓氏生成电子邮件地址

python - 使用 PyMongo 的 MongoDB Atlas 的 ServerTimeoutError(运行设置代码)

python - 无法登录我的用户,他们似乎没有正确注册

python - 如何向 openmdao 驱动程序添加整数变量?

python - For循环在Beautiful Soup中迭代div

python - 如何使用新版本的 pandas 读取从旧版本的 pandas 生成的 pickle 文件?

python - 闭包、部分和装饰器