Home »
Python
Extracting extension from filename in Python
By Sapna Deraje Radhakrishna Last updated : December 21, 2024
Python provides built in module to extract the file extension from the file name.
Before Python 3
The os.path module provides a function called splitext method, which splits the pathname path into file name and file extension.
Example
>>> import os
>>> file_name = 'includehelp.txt'
>>> print(os.path.splitext(file_name))
('includehelp', '.txt')
>>>
After Python 3
In the path from pathlib, using the suffix method.
Example
from pathlib import Path
# Define the file name
file_name = "example.txt"
# Get the file extension
file_extension = Path(file_name).suffix
# Print the file extension
print(file_extension)
Output
.txt