How to Get File Extension in Python With Examples

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.

Output:

File Extension in 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.

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.

By admin

Leave a Reply

%d bloggers like this: