Why on Windows, python3, os.path.abspath doesn't deal with leading slashes the same way if it's just a dir or if it's more?

Viewed 67

On Windows, python3:

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


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

on python2:

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


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

why is this the case?

And how would you deal with this, given that I have to compare paths together, and some are just like the first example, and others like the second?

The only horrible way I have to find this would be:

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")

So I end up having to do something like:

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("\\", "\\\\")
1 Answers

Actually, Python 3 is right and Python 2 is not. UNC paths must be composed of at least two "components":

  • a server or hostname
  • a share name

The server and the share name make up the volume.

more info here

Related