We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values - root and extension.
Here is a simple program to get the file extension in Python.
import os
# unpacking the tuple
file_name, file_extension = os.path.splitext("/Users/pankaj/abc.txt")
print(file_name)
print(file_extension)
print(os.path.splitext("/Users/pankaj/.bashrc"))
print(os.path.splitext("/Users/pankaj/a.b/image.png"))
Output:
We can also use pathlib module to get the file extension. This module was introduced in Python 3.4 release.
>>> import pathlib
>>> pathlib.Path("/Users/pankaj/abc.txt").suffix
'.txt'
>>> pathlib.Path("/Users/pankaj/.bashrc").suffix
''
>>> pathlib.Path("/Users/pankaj/.bashrc")
PosixPath('/Users/pankaj/.bashrc')
>>> pathlib.Path("/Users/pankaj/a.b/abc.jpg").suffix
'.jpg'
>>>
It’s always better to use the standard methods to get the file extension. If you are already using the os module, then use the splitext() method. For the object-oriented approach, use the pathlib module.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.