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

2023-05-04 15:54:54 +08:00
 sunamask

这是 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 这么设计的原因吗?

656 次点击
所在节点    问与答
3 条回复
jackyzy823
2023-05-04 16:09:06 +08:00
ovovovovo
2023-05-04 16:48:04 +08:00
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
2023-05-05 09:04:31 +08:00
@jackyzy823 作者也吃过亏…… "tripped me up in various ways",看来除了死记硬背之外没别的办法了……

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/937270

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX