使用 Python 获取文件的 mimetype
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14412211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the mimetype of a file with Python
提问by Navi
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.
我想确定一个 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)
回答by Blender
The error says that you have to initialize the MimeTypesclass:
该错误表示您必须初始化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)
Although you could skip this and use mimetypes.guess_typedirectly:
虽然你可以跳过这个mimetypes.guess_type直接使用:
>>> import urllib, mimetypes
>>>
>>> url = urllib.pathname2url('Upload.xml')
>>> print mimetypes.guess_type(url)
('application/xml', None)

