开发者

Get Filename Without Extension in Python

开发者 https://www.devze.com 2023-01-30 09:05 出处:网络
If I have a filename like one of these: 1.1.1.1.1.j开发者_开发技巧pg 1.1.jpg 1.jpg How could I get only the filename, without the extension? Would a regex be appropriate?In most cases, you should

If I have a filename like one of these:

1.1.1.1.1.j开发者_开发技巧pg

1.1.jpg

1.jpg

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


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.


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


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


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

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


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

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


One can also use the string slicing.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号