snippetpythonCritical
How do I get the filename without the extension from a path in Python?
Viewed 0 times
howextensionthegetpythonpathfilenamewithoutfrom
Problem
How do I get the filename without the extension from a path in Python?
"/path/to/some/file.txt" → "file"Solution
Python 3.4+
Use
Python < 3.4
Use
Use
pathlib.Path.stem>>> 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'Code Snippets
>>> from pathlib import Path
>>> Path("/path/to/file.txt").stem
'file'
>>> Path("/path/to/file.tar.gz").stem
'file.tar'>>> 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'Context
Stack Overflow Q#678236, score: 1937
Revisions (0)
No revisions yet.