Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of file extensions for a general file type?

I am trying to get a list of file extensions based upon the first part of a MIME type 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?

like image 966
david4dev Avatar asked Nov 27 '10 14:11

david4dev


1 Answers

I found the solution:

use:

mimetypes.init()

after importing the module.

This reads additional mime types from the operating system. (see python documentation)

like image 168
david4dev Avatar answered Oct 20 '22 19:10

david4dev