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.
