如何从Python中的路径获取不带扩展名的文件名?

"/path/to/some/file.txt"  →  "file"

当前回答

我想我会在不需要使用数组索引的情况下对os.path.splitext的使用做一个修改。

该函数始终返回(root,ext)对,因此可以安全使用:

root,ext=os.path.splitext(路径)

例子:

>>> import os
>>> path = 'my_text_file.txt'
>>> root, ext = os.path.splitext(path)
>>> root
'my_text_file'
>>> ext
'.txt'

其他回答

import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]

如果要保留文件的路径,只需删除扩展名

>>> file = '/root/dir/sub.exten/file.data.1.2.dat'
>>> print ('.').join(file.split('.')[:-1])
/root/dir/sub.exten/file.data.1.2

我们可以做一些简单的拆分/弹出魔术,如图所示(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
>>> print(os.path.splitext(os.path.basename("/path/to/file/hemanth.txt"))[0])
hemanth
import os
filename, file_extension =os.path.splitext(os.path.basename('/d1/d2/example.cs'))

文件名为“example”文件扩展名为“.cs”

'