【问题标题】:Get the mimetype of a file with Python使用 Python 获取文件的 mimetype
【发布时间】:2013-01-19 07:38:20
【问题描述】:

我想确定一个 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)

【问题讨论】:

标签: python


【解决方案1】:

错误说你必须初始化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)

【讨论】:

  • 更直接的方法是直接使用mimetypes.guess_type,而不是通过MimeTypes 实例。
  • @bdash:谢谢,我不知道。
  • @bdash 我在我的代码中尝试了同样的事情没有工作,请检查代码粘贴客栈问题
  • @devileye 您的代码没有按照我的建议执行。看看这个答案的第二部分。
  • 在 python 3.6 中:mimetypes.guess_type(path_file_to_upload)[1]
猜你喜欢
  • 2016-04-06
  • 2011-03-27
  • 2014-11-26
  • 1970-01-01
  • 2018-01-11
  • 2012-06-20
  • 2014-11-06
  • 2016-11-15
  • 1970-01-01
相关资源
最近更新 更多