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

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

当前回答

# 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,并且适用于复合文件类型和普通文件类型

其他回答

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

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

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
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)
import os
filename, file_extension =os.path.splitext(os.path.basename('/d1/d2/example.cs'))

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

'

获取不带扩展名的文件名:

import os
print(os.path.splitext("/path/to/some/file.txt")[0])

打印:

/path/to/some/file

os.path.splitext文档。

重要提示:如果文件名有多个点,则只删除最后一个点之后的扩展名。例如:

import os
print(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])

打印:

/path/to/some/file.txt.zip

如果您需要处理该案例,请参阅下面的其他答案。

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