How do I get the filename without the extension from a path in Python?
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Meditation
--
Chapters
00:00 How Do I Get The Filename Without The Extension From A Path In Python?
00:14 Accepted Answer Score 1868
00:38 Answer 2 Score 773
01:03 Answer 3 Score 279
01:10 Answer 4 Score 117
01:20 Thank you
--
Full question
https://stackoverflow.com/questions/6782...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #path
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Meditation
--
Chapters
00:00 How Do I Get The Filename Without The Extension From A Path In Python?
00:14 Accepted Answer Score 1868
00:38 Answer 2 Score 773
01:03 Answer 3 Score 279
01:10 Answer 4 Score 117
01:20 Thank you
--
Full question
https://stackoverflow.com/questions/6782...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #path
#avk47
ACCEPTED ANSWER
Score 1868
Python 3.4+
>>> from pathlib import Path
>>> Path("/path/to/file.txt").stem
'file'
>>> Path("/path/to/file.tar.gz").stem
'file.tar'
Python < 3.4
Use os.path.splitext in combination with os.path.basename:
>>> os.path.splitext(os.path.basename("/path/to/file.txt"))[0]
'file'
>>> os.path.splitext(os.path.basename("/path/to/file.tar.gz"))[0]
'file.tar'
ANSWER 2
Score 773
You can make your own with:
>>> import os
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'
Important note: If there is more than one . in the filename, only the last one is removed. For example:
/root/dir/sub/file.ext.zip -> file.ext
/root/dir/sub/file.ext.tar.gz -> file.ext.tar
See below for other answers that address that.
ANSWER 3
Score 279
>>> print(os.path.splitext(os.path.basename("/path/to/file/hemanth.txt"))[0])
hemanth
ANSWER 4
Score 117
In Python 3.4+ you can use the pathlib solution
from pathlib import Path
print(Path(your_path).resolve().stem)