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


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap