无论使用何种操作系统/路径格式,都可以从路径中提取文件名

无论操作系统或路径格式如何,我可以使用哪种Python库从路径提取文件名?

例如,我希望所有这些路径都能返回给我c

a/b/c/
a/b/c
abc
abc
abc
a/b/../../a/b/c/
a/b/../../a/b/c

在其他情况下使用os.path.splitos.path.basename将无法在任何情况下工作:如果您在Linux上运行脚本并尝试处理经典的Windows风格路径,则它将失败。

Windows路径可以使用反斜杠或正斜杠作为路径分隔符。 因此, ntpath模块(在windows上运行时相当于os.path)适用于所有平台上的所有(1)路径。

import ntpath
ntpath.basename("a/b/c")

当然,如果文件以斜线结尾,基本名称将是空的,因此请使用自己的函数来处理它:

def path_leaf(path):
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)

验证:

>>> paths = ['a/b/c/', 'a/b/c', 'abc', 'abc', 'abc', 
...     'a/b/../../a/b/c/', 'a/b/../../a/b/c']
>>> [path_leaf(path) for path in paths]
['c', 'c', 'c', 'c', 'c', 'c', 'c']


(1)有一个警告:Linux文件名可能包含反斜杠。 所以在Linux上, r'a/bc'总是指文件bca文件夹中,而在Windows,它始终指向c在文件b中的子文件夹a文件夹。 因此,当在一条路径中使用正斜杠和反斜杠时,您需要知道关联的平台能够正确解释它。 实际上,假设它是一个Windows路径通常是安全的,因为在Linux文件名中很少使用反斜杠,但是在编写代码时请记住这一点,以免造成意外的安全漏洞。


实际上,有一个函数返回你想要的

print(os.path.basename(your_path))

os.path.split是你正在寻找的功能

head, tail = os.path.split("/tmp/d/a.dat")

>>> print(tail)
a.dat
>>> print(head)
/tmp/d
链接地址: http://www.djcxy.com/p/20009.html

上一篇: Extract file name from path, no matter what the os/path format

下一篇: Use different Python version with virtualenv