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.