我想确定一个XML文件的mimetype,但是作为第一个参数,我得到了关于某个实例的错误信息。我是巨蟒新手,请帮忙。下面是我正在使用的代码及其引发的错误。
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)