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(".")
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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response