How to get the filename without the extension from a path in Python?
Getting the name of the file without the extension:
import osprint(os.path.splitext("/path/to/some/file.txt")[0])
Prints:
/path/to/some/file
Documentation for os.path.splitext
.
Important Note: If the filename has multiple dots, only the extension after the last one is removed. For example:
import osprint(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])
Prints:
/path/to/some/file.txt.zip
See other answers below if you need to handle that case.
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.