Categories
Python Answers

How to get the filename without the extension from a path in Python?

Spread the love

Sometimes, we want to get the filename without the extension from a path in Python.

In this article, we’ll look at how to get the filename without the extension from a path in Python.

How to get the filename without the extension from a path in Python?

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

For instance, we write:

import os

print(os.path.splitext("/path/to/some/file.txt")[0])

We call os.path.splittext with the "/path/to/some/file.txt" path string.

Then we get the path to the file without the extension with index 0 from the returned list.

Therefore, print should print '/path/to/some/file'.

Conclusion

To get the filename without the extension from a path 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 *