Python: Get just the filename without extension using Path

If you just want to get the file name without the extension from a file path then you can make use of the PurePath.stem method from the pathlib module.

Examples:

>>> from pathlib import PurePath
>>> 
>>> PurePath('my/data_compressed.tar.gz').stem
'data_compressed.tar'
>>> 
>>> PurePath('my/sales.xlsx').stem
'sales'
>>> 
>>> PurePath('my/2023_data.csv').stem
'2023_data'
>>> 
Python Get just the filename without extension using Path Examples

Example:

from pathlib import PurePath

data_file = '/mnt/data/2023.csv'

year_file = PurePath(data_file)
year = year_file.stem
print(year)
Output:

2023


Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!