In Python, we can extract the file extension using either of the two different approaches discussed below –
Method 1: Using Python os module splitext() function
This function splits the file path string into 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 to use when the OS module is being used already.
('my_file', '.txt') File Name: my_file File Extension: .txt
Method 2: Using Pathlib module
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.
File Extension: .txt
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course