如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
当前回答
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'
其他回答
导入操作系统
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)
我们可以做一些简单的拆分/弹出魔术,如图所示(https://stackoverflow.com/a/424006/1250044),以提取文件名(考虑windows和POSIX的差异)。
def getFileNameWithoutExtension(path):
return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0]
getFileNameWithoutExtension('/path/to/file-0.0.1.ext')
# => file-0.0.1
getFileNameWithoutExtension('\\path\\to\\file-0.0.1.ext')
# => file-0.0.1
获取不带扩展名的文件名:
import os
print(os.path.splitext("/path/to/some/file.txt")[0])
打印:
/path/to/some/file
os.path.splitext文档。
重要提示:如果文件名有多个点,则只删除最后一个点之后的扩展名。例如:
import os
print(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])
打印:
/path/to/some/file.txt.zip
如果您需要处理该案例,请参阅下面的其他答案。
为了方便起见,一个简单的函数包装了os.path中的两个方法:
def filename(path):
"""Return file name without extension from path.
See https://docs.python.org/3/library/os.path.html
"""
import os.path
b = os.path.split(path)[1] # path, *filename*
f = os.path.splitext(b)[0] # *file*, ext
#print(path, b, f)
return f
用Python 3.5测试。
在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'。