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

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

当前回答

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

其他回答

>>> print(os.path.splitext(os.path.basename("/path/to/file/hemanth.txt"))[0])
hemanth

我想我会在不需要使用数组索引的情况下对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'

我没有仔细看,但我没有看到任何人使用正则表达式解决这个问题。

我将问题解释为“给定路径,返回不带扩展名的基名称。”

e.g.

“path/to/file.json”=>“文件”

“path/to/my.file.json”=>“my.file”

在Python 2.7中,我们仍然没有pathlib。。。

def get_file_name_prefix(file_path):
    basename = os.path.basename(file_path)

    file_name_prefix_match = re.compile(r"^(?P<file_name_pre fix>.*)\..*$").match(basename)

    if file_name_prefix_match is None:
        return file_name
    else:
        return file_name_prefix_match.group("file_name_prefix")
get_file_name_prefix("path/to/file.json")
>> file

get_file_name_prefix("path/to/my.file.json")
>> my.file

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

在Python 3.4中使用来自pathlib的.stream+

from pathlib import Path

Path('/root/dir/sub/file.ext').stem

将返回

'file'

请注意,如果文件有多个扩展名,stem将只删除最后一个扩展名。例如,Path('file.tar.gz').stream将返回'file.tar'。