Get a filename without its extension in Python
Use Path.stem or splitext to remove the final suffix, and handle compound extensions without damaging hidden filenames.
Use Path(path).stem to get the last path component without its final suffix. With os.path, combine basename() and splitext().
Use pathlib
from pathlib import Path
path = Path('/home/user/archive.tar.gz')
assert path.stem == 'archive.tar'
assert path.name == 'archive.tar.gz'
assert path.suffix == '.gz'
assert path.suffixes == ['.tar', '.gz']
These operations inspect the path text; the file does not need to exist. Path uses the host operating system’s path conventions. To parse a Windows path on another platform, use PureWindowsPath.
Use os.path
import os
path = '/home/user/report.txt'
name = os.path.splitext(os.path.basename(path))[0]
assert name == 'report'
basename() removes the directory portion. splitext() separates the final extension.
Decide what a compound extension means
To remove every suffix reported by pathlib:
from pathlib import Path
import os
path = Path('/home/user/archive.tar.gz')
name = path.name
for _ in path.suffixes:
name = os.path.splitext(name)[0]
assert name == 'archive'
This also treats dots in names such as report.final.txt as suffix boundaries. If your task is specifically to remove .tar.gz, match that known suffix instead of stripping all dotted segments. Avoid name.split('.')[0]: it produces an empty result for .gitignore and discards meaningful parts of dotted filenames.
FAQ
What if the file has no extension?
Path('README').stem returns 'README'. os.path.splitext('README') returns ('README', '').
What happens to hidden files?
Path('.gitignore').stem is '.gitignore'; its leading dot is not treated as an extension separator. A hidden filename can still have a later suffix, as in .config.json.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan