Categories
Python Answers

How to extract the extension from the filename in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *