Skip to content
Related Articles

Related Articles

How to get file extension in Python?

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Jul, 2022

In this article, we will cover How to extract file extensions using Python, Get File Extension in Python we can use either of the two different approaches discussed below:

Method 1: Using Python os module splitext() function

This function splits the file path string into the file name and file extension into a pair of root and extension such that when both are added then we can retrieve the file path again (file_name + extension = path). This function is preferred use when the OS module is being used already.


import os
# this will return a tuple of root and extension
split_tup = os.path.splitext('my_file.txt')
# extract the file name and extension
file_name = split_tup[0]
file_extension = split_tup[1]
print("File Name: ", file_name)
print("File Extension: ", file_extension)


('my_file', '.txt')
File Name:  my_file
File Extension:  .txt

Method 2: Using Pathlib module

The pathlib.Path().suffix method of the Pathlib module can be used to extract the extension of the file path. This method is preferred for an object-oriented approach.


import pathlib
# function to return the file extension
file_extension = pathlib.Path('my_file.txt').suffix
print("File Extension: ", file_extension)


File Extension:  .txt
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!