What is the behavior of os.path.join() with UNC path?
What is the behavior of os.path.join() with UNC path?
Can someone explain the rules of joining path, I am confusing with these results:
print(os.path.join('\\192.168.1.1\A\B', 'C\D', '\E')) #\192.168.1.1AE, B,C,D are thrown away
print(os.path.join('\\192.168.1.1\', 'C\D', '\E')) #\192.168.1.1\E, C, D are thrown away
print(os.path.join('\\192.168.1.1', 'C\D', '\E')) #E, \192.168.1.1 is thrown away
print(os.path.join('C:\A\B', 'C\D', '\E')) #C:E, A, B, C, D are thrown away
os.path.join()
os.path.join()
2 Answers
2
An absolute path (like '\E'
) replaces the current path, rather than being appended to it.
'\E'
From [Python 3]: os.path.join(path, *paths):
...
If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
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
.
r'foo'
os.path.join("c:", "foo")
C:
(c:foo)
c:foo
So (in os.path.join()
), the last absolute path (and UNC path is absolute) discards any other path preceding it.
os.path.join()
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Don't use path separators in the arguments to
os.path.join()
. The whole point ofos.path.join()
is that it does that for you.– kindall
Sep 13 '18 at 3:25