如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
当前回答
在Python 3.4中使用来自pathlib的.stream+
from pathlib import Path
Path('/root/dir/sub/file.ext').stem
将返回
'file'
请注意,如果文件有多个扩展名,stem将只删除最后一个扩展名。例如,Path('file.tar.gz').stream将返回'file.tar'。
其他回答
我没有仔细看,但我没有看到任何人使用正则表达式解决这个问题。
我将问题解释为“给定路径,返回不带扩展名的基名称。”
e.g.
“path/to/file.json”=>“文件”
“path/to/my.file.json”=>“my.file”
在Python 2.7中,我们仍然没有pathlib。。。
def get_file_name_prefix(file_path):
basename = os.path.basename(file_path)
file_name_prefix_match = re.compile(r"^(?P<file_name_pre fix>.*)\..*$").match(basename)
if file_name_prefix_match is None:
return file_name
else:
return file_name_prefix_match.group("file_name_prefix")
get_file_name_prefix("path/to/file.json")
>> file
get_file_name_prefix("path/to/my.file.json")
>> my.file
get_file_name_prefix("path/to/no_extension")
>> no_extension
改进@spinup答案:
fn = pth.name
for s in pth.suffixes:
fn = fn.rsplit(s)[0]
break
print(fn) # thefile
这也适用于没有扩展名的文件名
在Python 3.4中使用来自pathlib的.stream+
from pathlib import Path
Path('/root/dir/sub/file.ext').stem
将返回
'file'
请注意,如果文件有多个扩展名,stem将只删除最后一个扩展名。例如,Path('file.tar.gz').stream将返回'file.tar'。
使用pathlib.Path.stem是正确的方法,但这里有一个丑陋的解决方案,它比基于pathlib的方法更有效。
您有一个文件路径,其字段由正斜杠/分隔,斜杠不能出现在文件名中,因此您将文件路径拆分为/,最后一个字段是文件名。
扩展名始终是通过按点分割文件名创建的列表的最后一个元素。,因此,如果反转文件名并按点拆分一次,则第二个元素的反转是不带扩展名的文件名。
name = path.split('/')[-1][::-1].split('.', 1)[1][::-1]
性能:
Python 3.9.10 (tags/v3.9.10:f2f3f53, Jan 17 2022, 15:14:21) [MSC v.1929 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.28.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from pathlib import Path
In [2]: file = 'D:/ffmpeg/ffmpeg.exe'
In [3]: Path(file).stem
Out[3]: 'ffmpeg'
In [4]: file.split('/')[-1][::-1].split('.', 1)[1][::-1]
Out[4]: 'ffmpeg'
In [5]: %timeit Path(file).stem
6.15 µs ± 433 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [6]: %timeit file.split('/')[-1][::-1].split('.', 1)[1][::-1]
671 ns ± 37.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [7]:
导入操作系统
filename = C:\\Users\\Public\\Videos\\Sample Videos\\wildlife.wmv
这将返回不带扩展名的文件名(C:\Users\Public\Videos\Sample Videos\wildlife)
temp = os.path.splitext(filename)[0]
现在,您可以使用
os.path.basename(temp) #this returns just the filename (wildlife)