sunamask
V2EX  ›  问与答

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

  •  
  •   sunamask · May 4, 2023 · 1478 views
    This topic created in 1111 days ago, the information mentioned may be changed or developed.

    这是 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 replies    2023-05-05 09:04:31 +08:00
    jackyzy823
        1
    jackyzy823  
       May 4, 2023   ❤️ 2
    ovovovovo
        2
    ovovovovo  
       May 4, 2023
    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
       May 5, 2023
    @jackyzy823 作者也吃过亏…… "tripped me up in various ways",看来除了死记硬背之外没别的办法了……
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3000 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 13:27 · PVG 21:27 · LAX 06:27 · JFK 09:27
    ♥ Do have faith in what you're doing.