94

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?

Will
  • 22,773
  • 13
  • 90
  • 102
user469652
  • 44,657
  • 57
  • 123
  • 163
  • Does this answer your question? [How to get the filename without the extension from a path in Python?](https://stackoverflow.com/questions/678236/how-to-get-the-filename-without-the-extension-from-a-path-in-python) – Seanny123 Jan 10 '20 at 21:02

5 Answers5

214

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.

Marcelo Cantos
  • 174,413
  • 38
  • 319
  • 360
  • 4
    Does not work properly with "git-1.7.8.tar.gz", where it only removes the ".gz". I use `basename[:-len(".tar.gz")]` for this. – blueyed Dec 09 '11 at 14:10
  • 28
    @blueyed: "Does not work properly" is a matter of perspective. The file *is* a gzip file, who's base name is `git-1.7.8.tar`. There is no way to correctly guess how many dots the caller wants to strip off, so `splitext()` only strips the last one. If you want to handle edge-cases like `.tar.gz`, you'll have to do it by hand. Obviously, you can't strip all the dots, since you'll end up with `git-1`. – Marcelo Cantos Dec 09 '11 at 22:29
27
>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')
Lennart Regebro
  • 158,668
  • 41
  • 218
  • 248
11

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
Vlad Bezden
  • 72,691
  • 22
  • 233
  • 168
10

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

s = re.sub(r'\.jpg$', '', s)
Alan Moore
  • 71,299
  • 12
  • 93
  • 154
6

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

os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')
Kenan Banks
  • 198,060
  • 33
  • 151
  • 170