Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.join in python returns 'wrong' path?

Tags:

python

os.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 find outputs 5, 6, 7 and 8 to be counterintuitive. Can somebody please explain if there was a specific reason for this implementation?

like image 659
Raghuram Onti Srinivasan Avatar asked Aug 08 '13 12:08

Raghuram Onti Srinivasan


People also ask

Why does os path join not work?

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.

What does os path join do in Python?

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.

How does Python solve path errors?

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.


1 Answers

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.

like image 78
Martijn Pieters Avatar answered Oct 10 '22 23:10

Martijn Pieters