windows系统上os.path.join()中的正斜杠和丢失参数

a6b3iqyw  于 2023-02-25  发布在  Windows
关注(0)|答案(1)|浏览(193)

我在Windows系统上工作,我想用os. path. join加入路径列表:
os.path.join('\\\\server\\directory', 'customer_files', 'other_directories', '/230221/12345.png')
但我得到的路径只连接第一个和最后一个参数:
'\\\\server\\directory/230221/12345.png'
我想得到的连接路径为:
'\\\\server\\directory\\customer_files\\other_directories\\230221/12345.png'
这里,server是连接到计算机网络的共享资源。directory是该共享系统中的目录。
如果去掉最后一个参数的正斜杠(/230221/12345.png230221/12345.png),就得到了预期的连接路径。
我的问题是:为什么我们只忽略正斜杠前面的中间路径,而不忽略第一条路径?
如果我们查看os. path. join的文档,它会说:
如果某个段是绝对路径(在Windows上需要驱动器和根),则会忽略之前的所有段,并从绝对路径段继续连接。
在Windows上,遇到根路径段(例如,r'\ foo')时不会重置驱动器。如果某个段位于其他驱动器上或者是绝对路径,则会忽略之前的所有段并重置驱动器
它是否考虑将'\\\\server\\directory'作为驱动器?如果是,为什么?

e0bqpujr

e0bqpujr1#

虽然文档中没有提到sharepoints,但是驱动器和sharepoints的含义与os.path.join类似,在os.path.join()的源代码中,我们可以看到每个路径段都经过os.path.splitdrive()函数,其中声明:

"""Split a pathname into drive/UNC sharepoint and relative path specifiers.
Returns a 2-tuple (drive_or_unc, path); either part may be empty.
...

If the path contained a UNC path, the drive_or_unc will contain the host name
and share up to but not including the fourth directory separator character.
e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")

因此,当遇到根路径段(在本例中为/230221/12345.png)时,\\server\directory保留(类似于驱动器),并且忽略根路径之前的所有其他路径段。

**注意:**如果我们进一步扩展路径\\server\computer,例如\\server\computer\another_directory,则只保留\\server\computer部分,而丢弃another_directory

相关问题