如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
当前回答
解决此问题的最简单方法是
import ntpath
print('Base name is ',ntpath.basename('/path/to/the/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)
但即使在导入os时,我也无法将其称为path.basename。是否可以直接将其称之为basename?
导入os,然后使用os.path.basename
导入os并不意味着你可以在不引用os的情况下使用os.foo。
import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]
解决此问题的最简单方法是
import ntpath
print('Base name is ',ntpath.basename('/path/to/the/file/'))
这节省了时间和计算成本。
其他方法不会删除多个扩展。有些文件名没有扩展名也有问题。这段代码处理这两个实例,在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