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

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

当前回答

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

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

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

其他回答

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

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

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

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

其他方法不会删除多个扩展。有些文件名没有扩展名也有问题。这段代码处理这两个实例,在Python2和Python3中都可以使用。它从路径中获取基名称,将值拆分为点,并返回第一个值,即文件名的初始部分。

import os

def get_filename_without_extension(file_path):
    file_basename = os.path.basename(file_path)
    filename_without_extension = file_basename.split('.')[0]
    return filename_without_extension

下面是一组要运行的示例:

example_paths = [
    "FileName", 
    "./FileName",
    "../../FileName",
    "FileName.txt", 
    "./FileName.txt.zip.asc",
    "/path/to/some/FileName",
    "/path/to/some/FileName.txt",
    "/path/to/some/FileName.txt.zip.asc"
]

for example_path in example_paths:
    print(get_filename_without_extension(example_path))

在任何情况下,打印的值为:

FileName

多扩展感知过程。适用于str和unicode路径。适用于Python 2和3。

import os

def file_base_name(file_name):
    if '.' in file_name:
        separator_index = file_name.index('.')
        base_name = file_name[:separator_index]
        return base_name
    else:
        return file_name

def path_base_name(path):
    file_name = os.path.basename(path)
    return file_base_name(file_name)

行为:

>>> path_base_name('file')
'file'
>>> path_base_name(u'file')
u'file'
>>> path_base_name('file.txt')
'file'
>>> path_base_name(u'file.txt')
u'file'
>>> path_base_name('file.tar.gz')
'file'
>>> path_base_name('file.a.b.c.d.e.f.g')
'file'
>>> path_base_name('relative/path/file.ext')
'file'
>>> path_base_name('/absolute/path/file.ext')
'file'
>>> path_base_name('Relative\\Windows\\Path\\file.txt')
'file'
>>> path_base_name('C:\\Absolute\\Windows\\Path\\file.txt')
'file'
>>> path_base_name('/path with spaces/file.ext')
'file'
>>> path_base_name('C:\\Windows Path With Spaces\\file.txt')
'file'
>>> path_base_name('some/path/file name with spaces.tar.gz.zip.rar.7z')
'file name with spaces'

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

以下是详细说明:

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

我的报告