Categories
Python Answers

How to extract extension from filename in Python?

Spread the love

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.

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 *