Get Filename Without Extension in Python

PythonRegex

Python Problem Overview


If I have a filename like one of these:

1.1.1.1.1.jpg

1.1.jpg

1.jpg

How could I get only the filename, without the extension? Would a regex be appropriate?

Python Solutions


Solution 1 - Python

In most cases, you shouldn't use a regex for that.

os.path.splitext(filename)[0]

This will also handle a filename like .bashrc correctly by keeping the whole name.

Solution 2 - Python

>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')

Solution 3 - Python

You can use stem method to get file name.

Here is an example:

from pathlib import Path

p = Path(r"\\some_directory\subdirectory\my_file.txt")
print(p.stem)
# my_file

Solution 4 - Python

If I had to do this with a regex, I'd do it like this:

s = re.sub(r'\.jpg$', '', s)

Solution 5 - Python

No need for regex. os.path.splitext is your friend:

os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser469652View Question on Stackoverflow
Solution 1 - PythonMarcelo CantosView Answer on Stackoverflow
Solution 2 - PythonLennart RegebroView Answer on Stackoverflow
Solution 3 - PythonVlad BezdenView Answer on Stackoverflow
Solution 4 - PythonAlan MooreView Answer on Stackoverflow
Solution 5 - PythonKenan BanksView Answer on Stackoverflow