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

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

当前回答

正如@IceAdor在对@user2902201的解决方案的评论中所指出的,rsplit是最简单的解决方案,它对多个周期都是健壮的(通过将拆分次数限制为maxsplit仅为1(从字符串末尾开始))。

以下是详细说明:

file = 'my.report.txt'
print file.rsplit('.', maxsplit=1)[0]

我的报告

其他回答

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

为了方便起见,一个简单的函数包装了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测试。

# use pathlib. the below works with compound filetypes and normal ones
source_file = 'spaces.tar.gz.zip.rar.7z'
source_path = pathlib.Path(source_file)
source_path.name.replace(''.join(source_path.suffixes), '')
>>> 'spaces'

尽管上面描述了许多工作实现,我还是添加了这个^,因为它只使用pathlib,并且适用于复合文件类型和普通文件类型

在Python 3.4+中,您可以使用pathlib解决方案

from pathlib import Path

print(Path(your_path).resolve().stem)

https://docs.python.org/3/library/os.path.html

在python 3中,pathlib“pathlib模块提供高级路径对象。”所以

>>> from pathlib import Path

>>> p = Path("/a/b/c.txt")
>>> p.with_suffix('')
WindowsPath('/a/b/c')
>>> p.stem
'c'