如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
如何从Python中的路径获取不带扩展名的文件名?
"/path/to/some/file.txt" → "file"
当前回答
改进@spinup答案:
fn = pth.name
for s in pth.suffixes:
fn = fn.rsplit(s)[0]
break
print(fn) # thefile
这也适用于没有扩展名的文件名
其他回答
改进@spinup答案:
fn = pth.name
for s in pth.suffixes:
fn = fn.rsplit(s)[0]
break
print(fn) # thefile
这也适用于没有扩展名的文件名
您可以通过以下方式制作自己的产品:
>>> 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
请参阅下面的其他答案来解决这个问题。
我们可以做一些简单的拆分/弹出魔术,如图所示(https://stackoverflow.com/a/424006/1250044),以提取文件名(考虑windows和POSIX的差异)。
def getFileNameWithoutExtension(path):
return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0]
getFileNameWithoutExtension('/path/to/file-0.0.1.ext')
# => file-0.0.1
getFileNameWithoutExtension('\\path\\to\\file-0.0.1.ext')
# => file-0.0.1
解决此问题的最简单方法是
import ntpath
print('Base name is ',ntpath.basename('/path/to/the/file/'))
这节省了时间和计算成本。
我已经阅读了答案,我注意到有很多好的解决方案。因此,对于那些希望获得(名称或扩展名)的人,这里有另一个解决方案,使用os模块,这两种方法都支持具有多个扩展名的文件。
import os
def get_file_name(path):
if not os.path.isdir(path):
return os.path.splitext(os.path.basename(path))[0].split(".")[0]
def get_file_extension(path):
extensions = []
copy_path = path
while True:
copy_path, result = os.path.splitext(copy_path)
if result != '':
extensions.append(result)
else:
break
extensions.reverse()
return "".join(extensions)
注意:windows上的此解决方案不支持带有“\”字符的文件名