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

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

当前回答

import os
filename, file_extension =os.path.splitext(os.path.basename('/d1/d2/example.cs'))

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

'

其他回答

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

多扩展感知过程。适用于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'

导入操作系统

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)

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

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

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

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