python os.path.basename_os.path.basename()不一致,我不知道为什么

这看起来像是Windows UNC的特殊性

UNC路径可以看作是unix路径的等价物,只是在开头有两个反斜杠。在

解决方法是使用经典的rsplit:>>> r"\\server\studies".rsplit(os.sep,1)[-1]

'studies'

有趣的事实:有3条路径可以正常工作:

^{pr2}$

为什么要这样?让我们检查一下windows上ntpath的源代码:

^{3}$

好了现在splitdef split(p):

seps = _get_bothseps(p)

d, p = splitdrive(p)

现在splitdrivedef splitdrive(p):

"""Split a pathname into drive/UNC sharepoint and relative path specifiers.

Returns a 2-tuple (drive_or_unc, path); either part may be empty.

仅仅阅读文档就可以让我们了解发生了什么。在

Windows sharepoint必须包含2个路径部分:\\server\shareroot

因此\\server\studies被视为驱动器,路径为空。当路径中有3个部分时不会发生。在

请注意,这不是一个bug,因为它不可能像普通目录一样使用\\server,在下面创建目录,等等。。。在

请注意,^{}的官方文档没有提到这一点(因为os.path在幕后调用ntpath),但它声明:Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program

最后强调的那部分至少是对的!(而且^{}的文档没有提到这个问题,甚至没有谈到windows)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值