用Python获取文件的mimetype
我想确定一个XML文件的MIME类型,但我得到关于某个实例作为第一个参数的错误。 我是新来的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)
链接地址: http://www.djcxy.com/p/46801.html