Menu Close

How to extract extension from filename in Python?

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 splitext method.

For instance, we write

import os

filename, file_extension = os.path.splitext('/path/to/somefile.ext')

to call os.path.splitext with the file path string that we to extract the file extension from.

We get the first file_extension from the 2nd item in the returned tuple.

Conclusion

To extract extension from filename in Python, we can use the splitext method.

Posted in Python, Python Answers