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) 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:

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