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

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

当前回答

导入操作系统

filename = C:\\Users\\Public\\Videos\\Sample Videos\\wildlife.wmv

这将返回不带扩展名的文件名(C:\Users\Public\Videos\Sample Videos\wildlife)

temp = os.path.splitext(filename)[0]  

现在,您可以使用

os.path.basename(temp)   #this returns just the filename (wildlife)

其他回答

我们可以做一些简单的拆分/弹出魔术,如图所示(https://stackoverflow.com/a/424006/1250044),以提取文件名(考虑windows和POSIX的差异)。

def getFileNameWithoutExtension(path):
  return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0]

getFileNameWithoutExtension('/path/to/file-0.0.1.ext')
# => file-0.0.1

getFileNameWithoutExtension('\\path\\to\\file-0.0.1.ext')
# => file-0.0.1

但即使在导入os时,我也无法将其称为path.basename。是否可以直接将其称之为basename?

导入os,然后使用os.path.basename

导入os并不意味着你可以在不引用os的情况下使用os.foo。

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

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

解决此问题的最简单方法是

import ntpath 
print('Base name is ',ntpath.basename('/path/to/the/file/'))

这节省了时间和计算成本。