How do I get the filename without the extension from a path in Python?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind
--
Chapters
00:00 Question
00:20 Accepted answer (Score 1683)
01:04 Answer 2 (Score 1113)
01:37 Answer 3 (Score 748)
02:11 Answer 4 (Score 269)
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/6782...
Accepted answer links:
[Documentation for ]: https://docs.python.org/3/library/os.pat...
Answer 2 links:
[.stem]: https://docs.python.org/3/library/pathli...
[pathlib]: https://docs.python.org/library/pathlib....
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #path
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind
--
Chapters
00:00 Question
00:20 Accepted answer (Score 1683)
01:04 Answer 2 (Score 1113)
01:37 Answer 3 (Score 748)
02:11 Answer 4 (Score 269)
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/6782...
Accepted answer links:
[Documentation for ]: https://docs.python.org/3/library/os.pat...
Answer 2 links:
[.stem]: https://docs.python.org/3/library/pathli...
[pathlib]: https://docs.python.org/library/pathlib....
--
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)