如何从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/'))
这节省了时间和计算成本。
其他回答
正如@IceAdor在对@user2902201的解决方案的评论中所指出的,rsplit是最简单的解决方案,它对多个周期都是健壮的(通过将拆分次数限制为maxsplit仅为1(从字符串末尾开始))。
以下是详细说明:
file = 'my.report.txt'
print file.rsplit('.', maxsplit=1)[0]
我的报告
但即使在导入os时,我也无法将其称为path.basename。是否可以直接将其称之为basename?
导入os,然后使用os.path.basename
导入os并不意味着你可以在不引用os的情况下使用os.foo。
解决此问题的最简单方法是
import ntpath
print('Base name is ',ntpath.basename('/path/to/the/file/'))
这节省了时间和计算成本。
多扩展感知过程。适用于str和unicode路径。适用于Python 2和3。
import os
def file_base_name(file_name):
if '.' in file_name:
separator_index = file_name.index('.')
base_name = file_name[:separator_index]
return base_name
else:
return file_name
def path_base_name(path):
file_name = os.path.basename(path)
return file_base_name(file_name)
行为:
>>> path_base_name('file')
'file'
>>> path_base_name(u'file')
u'file'
>>> path_base_name('file.txt')
'file'
>>> path_base_name(u'file.txt')
u'file'
>>> path_base_name('file.tar.gz')
'file'
>>> path_base_name('file.a.b.c.d.e.f.g')
'file'
>>> path_base_name('relative/path/file.ext')
'file'
>>> path_base_name('/absolute/path/file.ext')
'file'
>>> path_base_name('Relative\\Windows\\Path\\file.txt')
'file'
>>> path_base_name('C:\\Absolute\\Windows\\Path\\file.txt')
'file'
>>> path_base_name('/path with spaces/file.ext')
'file'
>>> path_base_name('C:\\Windows Path With Spaces\\file.txt')
'file'
>>> path_base_name('some/path/file name with spaces.tar.gz.zip.rar.7z')
'file name with spaces'
为了方便起见,一个简单的函数包装了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测试。