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?
如果没有扩展名,如何只获得文件名?regex是否合适?
4 个解决方案
#1
175
In most cases, you shouldn't use a regex for that.
在大多数情况下,您不应该为此使用regex。
os.path.splitext(filename)[0]
This will also handle a filename like .bashrc
correctly by keeping the whole name.
它还将通过保存整个文件名来正确地处理像.bashrc这样的文件名。
#2
21
>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')
#3
9
If I had to do this with a regex, I'd do it like this:
如果我要用正则表达式来做,我会这样做:
s = re.sub(r'\.jpg$', '', s)
#4
5
No need for regex. os.path.splitext
is your friend:
不需要正则表达式。os.path。splitext是你的朋友:
os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')
#1
175
In most cases, you shouldn't use a regex for that.
在大多数情况下,您不应该为此使用regex。
os.path.splitext(filename)[0]
This will also handle a filename like .bashrc
correctly by keeping the whole name.
它还将通过保存整个文件名来正确地处理像.bashrc这样的文件名。
#2
21
>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')
#3
9
If I had to do this with a regex, I'd do it like this:
如果我要用正则表达式来做,我会这样做:
s = re.sub(r'\.jpg$', '', s)
#4
5
No need for regex. os.path.splitext
is your friend:
不需要正则表达式。os.path。splitext是你的朋友:
os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')