Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the mimetype of a file with Python

Tags:

python

I want determine mimetype of an xml file , but I am getting error about some instance as first argument. I am new to python please help. Below is the code I am using and the error it throws.

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)
like image 366
Navi Avatar asked Jan 19 '13 07:01

Navi


1 Answers

The error says that you have to initialize the MimeTypes class:

>>> 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)

Although you could skip this and use mimetypes.guess_type directly:

>>> import urllib, mimetypes
>>> 
>>> url = urllib.pathname2url('Upload.xml')
>>> print mimetypes.guess_type(url)
('application/xml', None)
like image 141
Blender Avatar answered Oct 16 '22 22:10

Blender