13

我想确定一个 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)
4

1 回答 1

24

该错误表明您必须初始化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)
于 2013-01-19T07:41:22.240 回答