Get Filename Without Extension in Python

Question:

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?

Asked By: user469652

||

Answers:

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.

Answered By: Marcelo Cantos
>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')
Answered By: Lennart Regebro

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

os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')
Answered By: Kenan Banks

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

s = re.sub(r'.jpg$', '', s)
Answered By: Alan Moore

You can use stem method to get file name.

Here is an example:

from pathlib import Path

p = Path(r"\some_directorysubdirectorymy_file.txt")
print(p.stem)
# my_file
Answered By: Vlad Bezden

One can also use the string slicing.

>>> "1.1.1.1.1.jpg"[:-len(".jpg")]
'1.1.1.1.1'
Answered By: LetzerWille
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.