如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
当前回答
# 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,并且适用于复合文件类型和普通文件类型
其他回答
import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]
您可以通过以下方式制作自己的产品:
>>> import os
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'
重要提示:如果有多个。在文件名中,只删除最后一个。例如:
/root/dir/sub/file.ext.zip -> file.ext
/root/dir/sub/file.ext.tar.gz -> file.ext.tar
请参阅下面的其他答案来解决这个问题。
>>>print(os.path.splitext(os.paath.basename(“/path/to/file/vrun.txt”))[0])varun
这里/path/to/file/vrun.txt是文件的路径,输出为varun
import os
list = []
def getFileName( path ):
for file in os.listdir(path):
#print file
try:
base=os.path.basename(file)
splitbase=os.path.splitext(base)
ext = os.path.splitext(base)[1]
if(ext):
list.append(base)
else:
newpath = path+"/"+file
#print path
getFileName(newpath)
except:
pass
return list
getFileName("/home/weexcel-java3/Desktop/backup")
print list
导入操作系统
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)