When we receive a file from our users, it's frequently necessary to detect its type. Doing so through the filename without the need to actually read the data can be achieved through the mimetypes
module.
For this recipe, the following steps are to be performed:
- While the
mimetypes
module is not bullet proof, as it relies on the name of the file to detect the expected type, it's frequently enough to handle most common cases. - Users will usually assign proper names to their files for their own benefit (especially Windows users, where the extension is vital for the proper working of the file), guessing the type with
mimetypes.guess_type
is often enough:
import mimetypes def guess_file_type(filename): if not getattr(guess_file_type, 'initialised', False): mimetypes.init() guess_file_type.initialised = True file_type, encoding = mimetypes.guess_type(filename) return file_type
- We can call
guess_file_type
against any file to get...