如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
当前回答
导入操作系统
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)
其他回答
在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'。
import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]
在Python 3.4+中,您可以使用pathlib解决方案
from pathlib import Path
print(Path(your_path).resolve().stem)
在Windows系统上,我也使用了驱动程序名称前缀,例如:
>>> s = 'c:\\temp\\akarmi.txt'
>>> print(os.path.splitext(s)[0])
c:\temp\akarmi
因为我不需要驱动器号或目录名,所以我使用:
>>> print(os.path.splitext(os.path.basename(s))[0])
akarmi
正如@IceAdor在对@user2902201的解决方案的评论中所指出的,rsplit是最简单的解决方案,它对多个周期都是健壮的(通过将拆分次数限制为maxsplit仅为1(从字符串末尾开始))。
以下是详细说明:
file = 'my.report.txt'
print file.rsplit('.', maxsplit=1)[0]
我的报告