Python:- The best way to get file-type.
Jul 3, 2021
bad code to get file-type:-
filename = "abc/sample.txt"
filename_split_arr = filename.split(".")
print(filename_split_arr[-1])
best practice to get file-type:-
import magic
file_type = magic.from_file("abc/sample.txt", mime=True)
print(file_type)
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
.