How to use Python os module splitext() function In Python
This function splitext() 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.
Python3
import os # this will return a tuple of root and extension split_tup = os.path.splitext( 'my_file.txt' ) print (split_tup) # 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) |
Output:
('my_file', '.txt')
File Name: my_file
File Extension: .txt
How to get file extension in Python?
In this article, we will cover How to extract file extensions using Python.