Sometimes, we want to extract extension from filename in Python.
In this article, we’ll look at how to extract extension from filename in Python.
How to extract extension from filename in Python?
To extract extension from filename in Python, we can use the os.path.splittext
method.
For instance, we write:
import os
filename, file_extension = os.path.splitext('/path/to/somefile.ext')
print(file_extension)
We call os.path.splittext
with the path we want to extract the file extension from.
Then we get the file_extension
from the 2nd entry in the returned tuple.
Therefore, file_extension
is '.ext'
.
Conclusion
To extract extension from filename in Python, we can use the os.path.splittext
method.