How do I get the filename without the extension from a path in Python?
To get the filename without its extension in Python, use os.path.splitext() and os.path.basename():
This code gives you filename as 'example'.
Want to use Python's object-oriented approach instead? Here you go:
filename here will also return 'example'. Mind-blown, right?
os.path vs pathlib: Choose your Fighter
Classic os.path: Old is Gold
os.path is one part of the standard library and it has been providing a helping hand for longer. Dealing with legacy code or systems that don't recognize pathlib? os.path will be your knight in shining armor:
This will return 'some_file'—like magic, but not!
Modern pathlib: The Future is Here!
pathlib is a recent addition to Python and is in line with the object-oriented programming (OOP) paradigm. Starting a new Python project? pathlib is a great choice as it makes dealing with paths as easy as pie:
Bam! You get 'some_file', your filename without its extension.
Parsing Multiple File Extensions
Case of Multiple Dots in Filenames
When a file name has multiple dots, os.path.splitext() only removes the part after the final dot. This is useful when working with documents like archive.tar.gz :
This will return filename as 'archive.tar'.
Tricky pathlib Situation
When using pathlib, remember that .stem treats multiple extensions as part of the filename:
Here, filename will give you 'archive.tar'.
Find Your Path with pathlib
Relative paths or symbolic links? Python's pathlib allows you to resolve these to their absolute form and then get the filename:
And just like that, filename gives you 'file'.
Robust Path Handling: Be ready for anything!
Filenames with Spaces and Special Characters
Filenames with spaces or special characters? No problem. Wrap your file paths in quotes or use escape sequences:
Unicode filenames
Python supports Unicode filenames. Here's how pathlib would handle them:
Case Sensitivity
Remember that file paths could be case-sensitive depending on the operating system. Always check the case of your file when performing operations that include filename matches or uniqueness checks.
Was this article helpful?