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.


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


from pathlib import PurePath

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

year_file = PurePath(data_file)
year = year_file.stem



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

Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap