How To Check File Type Python

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

Step 2: Define a function to get the file type

Step 3: Test your function

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

Step 2: Define a function to get the file type

Step 3: Test your function

Output:

File type: text/plain

Step 4: Test your function with some other file types as well

Output:

File type: image/jpeg
File type: application/pdf

Full code

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.