I am trying to get a list of file extensions based upon the first part of a MIME ty开发者_StackOverflow社区pe using the mimetypes module. eg. 'image' is the first part of 'image/jpeg', 'image/png' etc.
This is my code:
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))
and this is the output:
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')
This is missing a lot of formats, eg. '.flac' for audio. mimetypes.types_map['.flac'].split('/')[0]
returns 'audio', so why is this not included in the output?
I found the solution:
use:
mimetypes.init()
after importing the module.
This reads additional mime types from the operating system. (see python documentation)
精彩评论