99

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
  • 24,082
  • 14
  • 97
  • 108
user469652
  • 48,855
  • 59
  • 128
  • 165
  • 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

6 Answers6

224

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
  • 181,030
  • 38
  • 327
  • 365
  • 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
  • 29
    @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
  • 167,292
  • 41
  • 224
  • 251
16

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
  • 83,883
  • 25
  • 248
  • 179
10

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

s = re.sub(r'\.jpg$', '', s)
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
6

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

os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')
Kenan Banks
  • 207,056
  • 34
  • 155
  • 173
0

One can also use the string slicing.

>>> "1.1.1.1.1.jpg"[:-len(".jpg")]
'1.1.1.1.1'
LetzerWille
  • 5,355
  • 4
  • 23
  • 26