在 Python 中获取没有扩展的文件名

如果我有这样的文件名:

1.1.1.1.1.jpg


1.1.jpg


1.jpg

如果没有扩展名,我怎么能只得到文件名? 正则表达式是否合适?

120311 次浏览

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')

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

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

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

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

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

One can also use the string slicing.

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