How to check file type?

QuestionsQuestions4 SkillsProAccess the Command LineAug, 31 2025
0352

To check the file type in Python, you can use the mimetypes module or the magic library. Here are examples of both methods:

Using mimetypes Module

import mimetypes

def get_file_type(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    return mime_type

file_path = 'example.txt'
print(get_file_type(file_path))

Using magic Library

First, you need to install the python-magic library if you haven't already:

pip install python-magic

Then you can use it as follows:

import magic

def get_file_type(file_path):
    mime = magic.Magic(mime=True)
    return mime.from_file(file_path)

file_path = 'example.txt'
print(get_file_type(file_path))

Both methods will help you determine the type of a file based on its content or extension.

0 Comments

no data
Be the first to share your comment!