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 find outputs 5, 6, 7 and 8 to be counterintuitive. Can somebody please explain if there was a specific reason for this implementation?
join function won't work if a component is an absolute path because all previous components are thrown away and joining continues from the absolute path component. The path strings shouldn't start with a slash. If they start with a slash, then they are believed an “absolute path” and everything before them is dumped.
path. join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator ('/') following each non-empty part except the last path component.
We can use double backslashes or \\ in place of single backslashes or \ to solve this issue. Refer to the following Python code for this. We can also use raw strings or prefix the file paths with an r instead of double backslashes.
From the os.path.join()
documentation:
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.
A /
at the start makes /tmp
an absolute path.
If you wanted to join multiple path elements that perhaps contain a leading path separator, then strip those first:
os.path.join(*(elem.lstrip(os.sep) for elem in elements))
Special-casing absolute paths makes it possible for you to specify either a relative path (from a default parent directory) or an absolute path and not have to detect if you have an absolute or relative path when constructing your final value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With