How do I get the filename without the extension from a path in Python?

How do I get the filename without the extension from a path in Python?

"/path/to/some/file.txt"  →  "file"

2
28

Use .stem from pathlib in Python 3.4+

from pathlib import Path

Path('/root/dir/sub/file.ext').stem

will return

'file'

Note that if your file has multiple extensions .stem will only remove the last extension. For example, Path('file.tar.gz').stem will return 'file.tar'.

Leave a Comment