Getting File Extension in Python
Here is a simple program to get the file extension in Python.
1 2 3 4 5 6 7 8 9 |
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 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.
1 2 3 4 5 6 7 8 9 10 11 12 |
>>> 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.