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

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

当前回答

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

其他回答

非常非常简单,没有其他模块!!!

import os
p = r"C:\Users\bilal\Documents\face Recognition python\imgs\northon.jpg"

# Get the filename only from the initial file path.
filename = os.path.basename(p)

# Use splitext() to get filename and extension separately.
(file, ext) = os.path.splitext(filename)

# Print outcome.
print("Filename without extension =", file)
print("Extension =", ext)

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

以下是详细说明:

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

我的报告

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

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

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

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'

我已经阅读了答案,我注意到有很多好的解决方案。因此,对于那些希望获得(名称或扩展名)的人,这里有另一个解决方案,使用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上的此解决方案不支持带有“\”字符的文件名