V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
sunamask
V2EX  ›  问与答

Python `os.path.basename()` 不忽略`'/$'` 的原因?

  •  
  •   sunamask · 364 天前 · 506 次点击
    这是一个创建于 364 天前的主题,其中的信息可能已经有所发展或是发生改变。

    这是 bash:

    ❯ basename /x/y/
    y
    ❯ basename /x/y
    y
    

    这是 R:

    > fs::path("/x/y") %>% fs::path_file()
    [1] "y"
    > fs::path("/x/y/") %>% fs::path_file()
    [1] "y"
    

    这是 python:

    >>> os.path.basename('/x/y')
    'y'
    >>> os.path.basename('/x/y/')
    ''
    

    并没有全面调查,不过我猜可能大多数脚本语言都和 bash 的行为相同。请问有谁知道 python 这么设计的原因吗?

    3 条回复    2023-05-05 09:04:31 +08:00
    ovovovovo
        2
    ovovovovo  
       364 天前
    os.path.basename(path)¶
    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; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string (''). 原因不知道,我只知道 doc 是这么介绍的
    sunamask
        3
    sunamask  
    OP
       364 天前
    @jackyzy823 作者也吃过亏…… "tripped me up in various ways",看来除了死记硬背之外没别的办法了……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2261 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 03:02 · PVG 11:02 · LAX 20:02 · JFK 23:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.