In this tutorial, we will learn how to check the file type of a given file using Python.
Knowing the file type is useful in various situations, such as when you want to filter specific files from a directory or apply different processing depending on the file format. We will explore two different methods to achieve this task: using the os and mimetypes libraries.
Method 1: Checking File Types using os Library
In the first method, we will use the os.path.splitext() function to obtain the file extension, which can give us an idea about the file type. Here are the steps:
Step 1: Import the required libraries
1 |
import os |
Step 2: Define a function to get the file type
1 2 |
def get_file_type(file_path): return os.path.splitext(file_path)[1] |
Step 3: Test your function
1 2 |
file_path = "example.txt" print("File type: ", get_file_type(file_path)) |
Output:
File type: .txt
Method 2: Checking File Types using mimetypes Library
In the second method, we will use the mimetypes.guess_type() function, which returns the file’s media type (MIME type) and encoding. This method gives more accurate information about the file type.
Step 1: Import the required libraries
1 |
import mimetypes |
Step 2: Define a function to get the file type
1 2 3 |
def get_file_type(file_path): mime_type, encoding = mimetypes.guess_type(file_path) return mime_type |
Step 3: Test your function
1 2 |
file_path = "example.txt" print("File type: ", get_file_type(file_path)) |
Output:
File type: text/plain
Step 4: Test your function with some other file types as well
1 2 3 4 5 |
file_path = "example.jpg" print("File type: ", get_file_type(file_path)) file_path = "example.pdf" print("File type: ", get_file_type(file_path)) |
Output:
File type: image/jpeg
File type: application/pdf
Full code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# Method 1: Using os library import os def get_file_type_method1(file_path): return os.path.splitext(file_path)[1] file_path = "example.txt" print("File type - Method 1: ", get_file_type_method1(file_path)) # Method 2: Using mimetypes library import mimetypes def get_file_type_method2(file_path): mime_type, encoding = mimetypes.guess_type(file_path) return mime_type file_path = "example.txt" print("File type - Method 2: ", get_file_type_method2(file_path)) file_path = "example.jpg" print("File type: ", get_file_type_method2(file_path)) file_path = "example.pdf" print("File type: ", get_file_type_method2(file_path)) |
Output
File type - Method 1: .txt File type - Method 2: text/plain File type: image/jpeg File type: application/pdf
Conclusion
In this tutorial, we learned two methods to check the file type in Python using the os and the mimetypes libraries.
The first method gives a basic idea about the file type by extracting the file extension, while the second method provides more accurate information about the file type by returning the MIME type.
Choose the method that suits your requirements best.