Python 3.x 在某些情况下,os.path.join提供不正确的输出

Python 3.x 在某些情况下,os.path.join提供不正确的输出,python-3.x,python-2.7,os.path,Python 3.x,Python 2.7,Os.path,我想使用os.path.join()函数合并两个路径。我要合并的路径是-'/Users/Tushar/Desktop/'和'/Exp' 我在做-os.path.join('/Users/Tushar/Desktop','/Exp')和 预期输出为-'/Users/Tushar/Desktop/Exp' 但实际上我得到了-'/Exp' 为什么我得到这个输出 这种输出出现在所有系统上,包括macOS、Windows和Linux 我试过了- os.path.join('/Users/Tushar/

我想使用os.path.join()函数合并两个路径。我要合并的路径是-
'/Users/Tushar/Desktop/'
'/Exp'

我在做-
os.path.join('/Users/Tushar/Desktop','/Exp')

  • 预期输出为-
    '/Users/Tushar/Desktop/Exp'

  • 但实际上我得到了-
    '/Exp'

为什么我得到这个输出

这种输出出现在所有系统上,包括macOS、Windows和Linux

我试过了-

  • os.path.join('/Users/Tushar/Desktop','Exp')
    我得到了正确的输出,即
    '/Users/Tushar/Desktop/Exp'

  • os.path.join('/Users/Tushar/Desktop/','Exp')
    我再次得到了正确的输出,即
    '/Users/Tushar/Desktop/Exp'

  • os.path.join('/Users/Tushar/Desktop','/Exp','/123')
    给出了
    '/123'
    ,但我期望的是
    '/Users/Tushar/Desktop/Exp/123'

  • 显然
    os.path.join('/Users/Tushar/Desktop/,'\\Exp')
    给出了正确的输出,即
    '/Users/Tushar/Desktop/\\Exp'
    其中as
    os.path.join('/Users/Tushar/Desktop/,'/Exp')
    给出了错误的输出
    '/Exp'

  • 到目前为止,我已经得出结论,它与“/Exp”末尾的斜杠(/)
    有关,这是导致此错误输出的原因。

    此行为是错误的

    如果某个组件是绝对路径,则会抛出以前的所有组件 “远离”和“连接”从绝对路径组件继续

    如果组件是绝对路径,则会丢弃所有以前的组件,并从绝对路径组件继续连接

    除第一个斜杠外,您需要手动去除所有组件中的所有前导斜杠:

    def my_join(根,*args):
    args=[args中arg的arg.lstrip(os.path.sep)]
    返回os.path.join(根,*args)
    
    见示例:

    >>我的加入('/home/ibug'、'/oh'、'/yeah'、'/hasty')
    “/家/ibug/哦/是的/很帅”