How to get the filename without the extension from a path in Python?
For instance, if I had "/path/to/some/file.txt"
, I would want "file"
.
Getting the name of the file without the extension:
import os
print(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 os
print(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.
If this is a common enough operation, perhaps it should merit it's own official command? Something like os.path.filename(path_to_file) instead of os.path.splitext(os.path.basename(path_to_file))[0]
What if the filename contains multiple dots?
For anyone wondering the same as matteok, if there are multiple dots, splitext splits at the last one (so
splitext('kitty.jpg.zip')
gives('kitty.jpg', '.zip')
).Note that this code returns the complete file path (without the extension), not just the file name.
yeah, so you'd have to do
splitext(basename('/some/path/to/file.txt'))[0]
(which i always seem to be doing)