Tutorial

How to Get File Extension in Python

Published on August 3, 2022
Default avatar

By Pankaj

How to Get File Extension in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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.

Getting File Extension in Python

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:

File Extension Python
File Extension in Python
  • In the first example, we are directly unpacking the tuple values to the two variables.
  • Note that the .bashrc file has no extension. The dot is added to the file name to make it a hidden file.
  • In the third example, there is a dot in the directory name.

Get File Extension using Pathlib Module

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'
>>> 

Conclusion

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.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel