如何从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)
其他回答
>>> print(os.path.splitext(os.path.basename("/path/to/file/hemanth.txt"))[0])
hemanth
如果扩展名中有多个点,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
import os
filename, file_extension =os.path.splitext(os.path.basename('/d1/d2/example.cs'))
文件名为“example”文件扩展名为“.cs”
'
解决此问题的最简单方法是
import ntpath
print('Base name is ',ntpath.basename('/path/to/the/file/'))
这节省了时间和计算成本。
import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]