首页 > 解决方案 > 为什么在 Windows 上,python3,os.path.abspath 不以相同的方式处理前导斜杠,如果它只是一个 dir 或更多?

问题描述

在 Windows 上,python3:

>>> print(os.path.abspath("//foo/foo.txt"))
\\foo\foo.txt


>>> print(os.path.abspath("//foo"))
\foo

在 python2 上:

>>> print(os.path.abspath("//foo/foo.txt"))
\\foo\foo.txt


>>> print(os.path.abspath("//foo"))
\\foo

为什么会这样?

鉴于我必须将路径一起比较,有些就像第一个例子,有些像第二个例子,你会如何处理这个问题?

我必须找到的唯一可怕的方法是:

In [34]: re.match(r"^(//|\\\\)(?!.+(/|\\))", "//foo")
Out[34]: <re.Match object; span=(0, 2), match='//'>
 
In [35]: re.match(r"^(//|\\\\)(?!.+(/|\\))", "\\\\foo")
Out[35]: <re.Match object; span=(0, 2), match='\\\\'>
 
In [36]: re.match(r"^(//|\\\\)(?!.+(/|\\))", "//foo/bar")
 
In [37]: re.match(r"^(//|\\\\)(?!.+(/|\\))", "\\\\foo\\bar")

所以我最终不得不做类似的事情:

file_path = "//foo"
match = False
if re.match(r"^(//|\\\\)(?!.+(/|\\))", file_path):
  match = True
file_path = os.path.abspath(file_path)
if match:
  file_path = file_path.replace("\\", "\\\\")

标签: pythonpython-3.xwindowsos.path

解决方案


实际上,Python 3 是对的,而 Python 2 不是。UNC 路径必须由至少两个“组件”组成:

  • 服务器或主机名
  • 共享名称

服务器和共享名组成卷。

更多信息在这里


推荐阅读