如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
当前回答
如果扩展名中有多个点,os.path.splitext()将无法工作。
例如,images.tar.gz
>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> print os.path.splitext(file_name)[0]
images.tar
您只需找到basename中第一个点的索引,然后对basename进行切片,即可获得不带扩展名的文件名。
>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> index_of_dot = file_name.index('.')
>>> file_name_without_extension = file_name[:index_of_dot]
>>> print file_name_without_extension
images
其他回答
在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
import os
filename, file_extension =os.path.splitext(os.path.basename('/d1/d2/example.cs'))
文件名为“example”文件扩展名为“.cs”
'
其他方法不会删除多个扩展。有些文件名没有扩展名也有问题。这段代码处理这两个实例,在Python2和Python3中都可以使用。它从路径中获取基名称,将值拆分为点,并返回第一个值,即文件名的初始部分。
import os
def get_filename_without_extension(file_path):
file_basename = os.path.basename(file_path)
filename_without_extension = file_basename.split('.')[0]
return filename_without_extension
下面是一组要运行的示例:
example_paths = [
"FileName",
"./FileName",
"../../FileName",
"FileName.txt",
"./FileName.txt.zip.asc",
"/path/to/some/FileName",
"/path/to/some/FileName.txt",
"/path/to/some/FileName.txt.zip.asc"
]
for example_path in example_paths:
print(get_filename_without_extension(example_path))
在任何情况下,打印的值为:
FileName
>>> print(os.path.splitext(os.path.basename("/path/to/file/hemanth.txt"))[0])
hemanth
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