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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4444923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:46:19  来源:igfitidea点击:

Get Filename Without Extension in Python

pythonregex

提问by user469652

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?

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

采纳答案by Marcelo Cantos

In most cases, you shouldn't use a regex for that.

在大多数情况下,您不应该为此使用正则表达式。

os.path.splitext(filename)[0]

This will also handle a filename like .bashrccorrectly by keeping the whole name.

这也将.bashrc通过保留全名来正确处理文件名。

回答by Lennart Regebro

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

回答by Triptych

No need for regex. os.path.splitextis your friend:

不需要正则表达式。os.path.splitext是你的朋友:

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

回答by Alan Moore

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

如果我必须用正则表达式来做这件事,我会这样做:

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

回答by Vlad Bezden

You can use stemmethod to get file name.

您可以使用stem方法获取文件名。

Here is an example:

下面是一个例子:

from pathlib import Path

p = Path(r"\some_directory\subdirectory\my_file.txt")
print(p.stem)
# my_file