使用Python获取文件的mimetype

Nav*_*avi 12 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)
Run Code Online (Sandbox Code Playgroud)

Ble*_*der 23

错误说你必须初始化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)
Run Code Online (Sandbox Code Playgroud)

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

>>> import urllib, mimetypes
>>> 
>>> url = urllib.pathname2url('Upload.xml')
>>> print mimetypes.guess_type(url)
('application/xml', None)
Run Code Online (Sandbox Code Playgroud)

  • 更直接的方法是直接使用`mimetypes.guess_type`而不是通过`MimeTypes`实例. (6认同)