How to extract the extension from the filename in Python?

Sometimes, we want to extract the extension from the filename in Python.

In this article, we’ll look at how to extract the extension from the filename in Python.

How to extract the extension from the filename in Python?

To extract the extension from the 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 string we want to extract the file extension from.

Then we take the file_extension from the returned tuple.

Therefore, file_extension is '.ext'.

Conclusion

To extract the extension from the filename in Python, we can use the os.path.splittext method.