在Python中获取具有预定扩展名的文件基本名称 [英] Obtaining file basename with a prespecified extension in Python
问题描述
我有以下字符串:
/path1/path2/foo.bar.qux.txt
我想要做的是通过指定扩展名来提取基本名称.如果我将扩展名定义为 .bar.qux.txt
,则基本名称为" foo
".然后,如果扩展名是 .qux.txt
,则基址是: foo.bar
.
What I want to do is to extract the basename by specifying the extension.
If I define the extension to be .bar.qux.txt
then the base name is "foo
".
Then if the extension is .qux.txt
then the base is: foo.bar
.
Perl具有以下功能:
Perl has the following function:
use File::Basename;
my $longones = "/path1/path2/foo.bar.qux.txt";
my $base = basename($longones,"*.bar.qux.txt");
print "$base\n";
Python的实现方式是什么?
What's the Python way to do it?
推荐答案
没有内置函数可以满足您的需求. os.path.splitext
不允许定义应被视为扩展名的内容.实际上,perl函数的名称 basename
是一个错误的名称,因为在* NIX basename
中中包含扩展名.
There's no built-in function that does what you want. os.path.splitext
doesn't allow to define what should be considered an extension. In fact the name basename
for the perl function is a misnaming because in *NIX basename
does contain the extension.
不过,您可以组合 os.path.basename
和 rsplit
:
However you can combine os.path.basename
with a rsplit
:
>>> import os
>>> os.path.basename('/path1/path2/foo.bar.qux.txt').rsplit('.bar.qux.txt')[0]
'foo'
>>> os.path.basename('/path1/path2/foo.bar.qux.txt').rsplit('.qux.txt')[0]
'foo.bar'
请注意,如果文件名包含扩展名,则可能会得到错误的结果:
Note that if the filename contains the extension you might get a wrong result:
>>> os.path.basename('/path1/path2/foo.bar.qux.txt.foo.bar.qux.txt').rsplit('.qux.txt')[0]
'foo.bar'
不过,您始终可以将 1
的 maxsplit
指定为仅拆分第一个扩展名:
However you can always specify a maxsplit
of 1
to only split the first extension:
>>> os.path.basename('/path1/path2/foo.bar.qux.txt.foo.bar.qux.txt').rsplit('.qux.txt', maxsplit=1)[0]
'foo.bar.qux.txt.foo.bar'
在python2中,您必须在位置上将第二个参数指定为 rsplit(text,1)
.
或者使用 rpartition
:
>>> os.path.basename('/path1/path2/foo.bar.qux.txt.foo.bar.qux.txt').rpartition('.qux.txt')[0]
'foo.bar.qux.txt.foo.bar'
使用正则表达式的解决方案可能是:
A solution with regexes could be:
import re
def basename_without_ext(path, ext):
regex = re.compile('{}$'.format(re.escape(ext)))
return regex.sub('', os.path.basename(path))
用作:
>>> basename_without_ext('/path1/path2/foo.bar.qux.txt.foo.bar.qux.txt', '.qux.txt')
'foo.bar.qux.txt.foo.bar'
>>> basename_without_ext('/path1/path2/foo.bar.qux.txt', '.bar.qux.txt')
'foo'
这篇关于在Python中获取具有预定扩展名的文件基本名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!