7

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Note that there isn't *any* reason to have an absolute path as non-first argument to `join`. `join` is meant to build *a* path given its components. No path has absolute paths as "sub-path". What would you expect to happen with `join("/", "/tmp")`? – Bakuriu Aug 08 '13 at 12:21
  • makes sense! i guess that justifies the implementation well! thanks! – Raghuram Onti Srinivasan Aug 08 '13 at 18:57

2 Answers2

19

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

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.

Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71