Does python OS.path.join return the "wrong" path?

I have the following python os.path output from ipython

import os.path as path path.join("/", "tmp") Out[4]: '/tmp' path.join("/", "/tmp") Out[5]: '/tmp' path.join("abc/", "/tmp") Out[6]: '/tmp' path.join("abc", "/tmp") Out[7]: '/tmp' path.join("/abc", "/tmp") Out[8]: '/tmp' path.join("def", "tmp") Out[10]: 'def/tmp' 

I believe that outputs 5, 6, 7, and 8 contradict each other. Can someone explain if there is a specific reason for this implementation?

+4
source share
2 answers

From the os.path.join() documentation :

Combine one or more path components intellectually. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if any) are discarded, and the connection continues.

A / at the beginning makes /tmp an absolute path.

If you want to combine multiple path elements that may contain a leading path separator, first separate them:

 os.path.join(*(elem.lstrip(os.sep) for elem in elements)) 

Absolute paths with special casing allow you to specify either a relative path (from the parent directory by default) or an absolute path and should not determine whether you have an absolute or relative path when building the final value.

+15
source

The second line should not start with / ; which creates an absolute path . The following has been done:

 >>> path.join('abc/', 'tmp') 'abc/tmp' 

From the Python documentation:

If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if any) are discarded, and the connection continues.

+3
source

Source: https://habr.com/ru/post/1495940/


All Articles