Python:- The best way to get file-type.

sohesh doshi
Jul 3, 2021

bad code to get file-type:-

filename = "abc/sample.txt"
filename_split_arr = filename.split(".")

best practice to get file-type:-

import magic
file_type = magic.from_file("abc/sample.txt", mime=True)

python-magic is a Python interface to the libmagic file type identification library. libmagic identifies file types by checking their headers according to a predefined list of file types. This functionality is exposed to the command line by the Unix command file.