2013-01-19 104 views
11

我想確定一個xml文件的mimetype,但是我收到有關某個實例作爲第一個參數的錯誤。我是新來的python請幫忙。下面是我正在使用的代碼和它引發的錯誤。用Python獲取文件的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) 

回答

20

錯誤說,你必須初始化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) 
+5

更直接的方法是使用' mimetypes.guess_type「,而不是通過」MimeTypes「實例。 – bdash

+0

@bdash:謝謝,我不知道。 – Blender

+0

@bdash我在我的代碼嘗試相同的東西沒有工作,請檢查代碼粘貼客棧問題 – Navi