如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
当前回答
在Python 3.4+中,您可以使用pathlib解决方案
from pathlib import Path
print(Path(your_path).resolve().stem)
其他回答
导入操作系统
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)
在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
如果要保留文件的路径,只需删除扩展名
>>> file = '/root/dir/sub.exten/file.data.1.2.dat'
>>> print ('.').join(file.split('.')[:-1])
/root/dir/sub.exten/file.data.1.2
https://docs.python.org/3/library/os.path.html
在python 3中,pathlib“pathlib模块提供高级路径对象。”所以
>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> p.with_suffix('')
WindowsPath('/a/b/c')
>>> p.stem
'c'
# use pathlib. the below works with compound filetypes and normal ones
source_file = 'spaces.tar.gz.zip.rar.7z'
source_path = pathlib.Path(source_file)
source_path.name.replace(''.join(source_path.suffixes), '')
>>> 'spaces'
尽管上面描述了许多工作实现,我还是添加了这个^,因为它只使用pathlib,并且适用于复合文件类型和普通文件类型