gpt4 book ai didi

python - 为什么 os.path.basename 在传递带有尾部斜杠的路径时返回空字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:26 30 4
gpt4 key购买 nike

os.path.basename 的参数中使用尾随目录定界符会产生空字符串是否有原则性原因?除了看起来像未处理的实现边缘情况或实现副作用之外,我不确定我能否理解该返回值。

>>> import os
>>> os.path.basename('/tmp')
'tmp'
>>> os.path.basename('/tmp/')
''

最佳答案

basename 的文档说明了这一点:

Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split().

os.path.split 的文档是这样说的(添加了强调):

Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty.

"/tmp/" 上调用 os.path.split 会产生 ('/tmp', '')。因为该对的第二个元素是 '',所以 basename 返回 ''

关于python - 为什么 os.path.basename 在传递带有尾部斜杠的路径时返回空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54950875/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com