101

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?

1

6 Answers 6

225

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: "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.
27
>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')

Comments

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

Comments

10

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

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

Comments

6

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

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

Comments

0

One can also use the string slicing.

>>> "1.1.1.1.1.jpg"[:-len(".jpg")]
'1.1.1.1.1'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.