How can i get a file extension from a filetype?

Question:

I have a list of filenames as follows

files = [
    '/dl/files/4j55eeer_wq3wxxpiqm.jpg',
    '/home/Desktop/hjsd03wnsbdr9rk3k',
    'kd0dje7cmidj0xks03nd8nd8a3',
    ...
]

The problem is most of the files do not have an extension in the filenames, what would be the best way to get file extension of these files ?

I don’t know if this is even possible because python would treat all files as buffer or string objects that do not have any filetype associated with them.

can this be done at all ?

Asked By: Amyth

||

Answers:

It can be done if you have an oracle that determines file types from their content. Happily at least one such oracle is already implemented in Python: https://github.com/ahupp/python-magic

Answered By: John Zwinck

Once you use magic to get the MIME type, you can use mimetypes.guess_extension() to get the extension for it.

The below code worked for me :

import filetype

fileinfo = filetype.guess(mock.jpg) #the argument can be buffer/file
detectedExt = fileinfo.extension
detectedmime = fileinfo.mime

filetype package documentation

Answered By: Pavithra B
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.