Get filename without extension in Python
This post will discuss how to get a filename without an extension from the specified path in Python.
1. Using os.path.splitext() function
The standard solution is to use the os.path.splitext(path) function to split a path into a (root, ext) pair such that root + ext == path. This returns the path to the file without extension. If the file has multiple periods, leading periods are ignored.
|
1 2 3 4 5 |
import os dir = '/path/to/some/file.txt' print(os.path.splitext(dir)[0]) # /path/to/some/ |
2. Using str.rsplit() function
Alternatively, you can use the str.rsplit() function to split on the last period.
|
1 2 3 |
dir = '/path/to/some/file.txt' print(dir.rsplit('.', 1)[0]) # /path/to/some/ |
3. Using pathlib.Path.stem() function
If you don’t need the complete path, you can use the pathlib module in Python 3.4+. You can use its stem property that returns the file name without its extension:
|
1 2 3 4 5 |
from pathlib import Path dir = '/path/to/some/file.txt' print(Path(dir).stem) # /path/to/some/ |
That’s all about getting filename without extension in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)