Here are 3 ways to extract the file extension using Python:
(1) Extract the file extension with the dot:
import os.path file_path = r"path where the file is stored\file_name.file_extension" file_extension = os.path.splitext(file_path)[1] print(file_extension)
(2) Extract the file extension without the dot:
import os.path file_path = r"path where the file is stored\file_name.file_extension" file_extension = os.path.splitext(file_path)[1][1:] print(file_extension)
(3) Extract both the root and the file extension:
import os.path file_path = r"path where the file is stored\file_name.file_extension" file_extension = os.path.splitext(file_path) print(file_extension)
3 Scenarios to Extract the File Extension using Python
Scenario 1: Extract the file extension with the dot
Under the first scenario, you’ll observe how to extract the file extension with the dot.
To start with a simple example, let’s suppose that a text file (called ‘products‘) is stored under the following path:
To extract the file extension with the dot using Python:
import os.path file_path = r"C:\Users\Ron\Desktop\Test\products.txt" file_extension = os.path.splitext(file_path)[1] print(file_extension)
The file extension is “.txt” with the dot:
.txt
Scenario 2: Extract the file extension without the dot
To extract the file extension without the dot:
import os.path file_path = r"C:\Users\Ron\Desktop\Test\products.txt" file_extension = os.path.splitext(file_path)[1][1:] print(file_extension)
The file extension is now “txt” without the dot:
txt
Scenario 3: Extract both the root and the file extension
To extract both the root and the file extension:
import os.path file_path = r"C:\Users\Ron\Desktop\Test\products.txt" file_extension = os.path.splitext(file_path) print(file_extension)
The result:
('C:\\Users\\Ron\\Desktop\\Test\\products', '.txt')
Finally, you may check the os.path Documentation to learn more about os.path.splitext.