Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

The second strings should not start with a /; that creates an absolute path. Doing the following worked:

>>> 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 there was one) are thrown away, and joining continues.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top