【问题标题】:How to get a list of file extensions for a general file type?如何获取通用文件类型的文件扩展名列表?
【发布时间】:2011-05-16 13:49:16
【问题描述】:

我正在尝试使用 mimetypes 模块根据 MIME 类型的第一部分获取文件扩展名列表。例如。 'image' 是 'image/jpeg'、'image/png' 等的第一部分。

这是我的代码:

import mimetypes

def get_extensions_for_type(general_type):
    for ext in mimetypes.types_map:
        if mimetypes.types_map[ext].split('/')[0] == general_type:
            yield ext

VIDEO = tuple(get_extensions_for_type('video'))
AUDIO = tuple(get_extensions_for_type('audio'))
IMAGE = tuple(get_extensions_for_type('image'))

print("VIDEO = " + str(VIDEO))
print('')
print("AUDIO = " + str(AUDIO))
print('')
print("IMAGE = " + str(IMAGE))

这是输出:

VIDEO = ('.m1v', '.mpeg', '.mov', '.qt', '.mpa', '.mpg', '.mpe', '.avi', '.movie', '.mp4')

AUDIO = ('.ra', '.aif', '.aiff', '.aifc', '.wav', '.au', '.snd', '.mp3', '.mp2')

IMAGE = ('.ras', '.xwd', '.bmp', '.jpe', '.jpg', '.jpeg', '.xpm', '.ief', '.pbm', '.tif', '.gif', '.ppm', '.xbm', '.tiff', '.rgb', '.pgm', '.png', '.pnm')

这缺少很多格式,例如。 '.flac' 用于音频。 mimetypes.types_map['.flac'].split('/')[0] 返回 'audio',为什么不包含在输出中?

【问题讨论】:

  • 哪个版本的 Python?我已经尝试了 2.6 和 3.1,并且 mimetypes.types_map 不包含“.flac”。

标签: python iterator mime-types


【解决方案1】:

我找到了解决办法:

使用:

mimetypes.init()

导入模块后。

这会从操作系统读取其他 mime 类型。 (see python documentation)

【讨论】:

猜你喜欢
  • 2013-05-28
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 2011-06-04
  • 1970-01-01
  • 2011-05-27
  • 2011-07-29
相关资源
最近更新 更多