Skip to main content
 首页 » 编程设计

python之Python 的 os.path.join() 的正确结果

2025年05月04日1198°冷暖

阅读 os.path.join() 方法的在线文档后,以下情况似乎应该符合条件,但显然不符合条件。我是否正确阅读了该文档?

>>> import os 
>>> 
>>> os.path.join("/home/user", "/projects/pyproject", "mycode.py") 
>>> '/projects/pyproject/mycode.py' 

在第一条和第二条路径上尝试不同的尾随和前导 os.sep 组合后,似乎要加入的第二条路径的第一个字符不能以 os.sep 开头。

>>> os.path.join("/home/user", "projects/pyproject", "mycode.py") 
>>> '/home/user/projects/pyproject/mycode.py' 

在 path1 和 path2 是来自用户输入的部分的情况下,意味着编写代码来解析他们的输入以获得领先的 os.sep。

来自 python.org 在线引用:

os.path.join(path1[, path2[, ...]]) Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) following each non-empty part except the last. (This means that an empty last part will result in a path that ends with a separator.) Note that on Windows, 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.

请您参考如下方法:

Am I reading that documentation correctly?

再读一遍,强调我的:

Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) following each non-empty part except the last. (This means that an empty last part will result in a path that ends with a separator.) Note that on Windows, 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.

当它说以前的组件被“丢弃”时,意味着它们被忽略并且不包含在最终结果中。