Python os.path.join 以 ("any_path", "c:\") 作为输入的奇怪行为

Python os.path.join weird behaviour with ("any_path", "c:\") as input

所以,我正在制作一个伪登录系统,并且 运行 遇到了 os.path.join 函数的一些错误。

当输入 "c:" 或 "d:" 作为用户名时,它似乎表现得很奇怪,因为它使根驱动器之前的任何路径字符串无效。

因此,输入如下:

>>> import os
>>> os.path.exists( os.path.join( some_path, "this_is", "voided", "c:", "python34" ) )
True

将完全忽略其前 3 个语句。

有什么办法可以避免这种情况吗?

似乎是一个已知的 bug

On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

你可以试试pathlib.PurePath.joinpath