Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does os.path.join throw away arguments?

I'm learning Python and I noticed something strange with one of my scripts. Doing a little testing I discovered the problem stemmed from this behavior:

>>> import os
>>> os.path.join('a','b')
'a/b'
>>> os.path.join('a','/b')
'/b'

Checking the documentation, this is, in fact, the design of the function:

os.path.join(path1[, path2[, ...]])

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. ...

My question isn't why my script failed, but rather why the function was designed this way. I mean, on Unix at least, a//b is a perfectly acceptable way to designate a path, if not elegant. Why was the function designed this way? Is there any way to tell if one or more path elements have been discarded short of testing each path string with os.path.isabs()?


Out of curiosity, I also checked the case where a path component ends in an os.sep character:

>>> os.path.join('a/','b')
'a/b'

That works as expected.

like image 433
Jon Ericson Avatar asked Sep 26 '12 19:09

Jon Ericson


2 Answers

One case where it is useful for os.path.join('a', '/b') to return /b would be if you ask a user for a filename.

The user can enter either a path relative to the current directory, or a full path, and your program could handle both cases like this:

os.path.join(os.getcwd(), filename)

In [54]: os.getcwd()
Out[54]: '/tmp'

In [55]: os.path.join(os.getcwd(), 'foo')
Out[55]: '/tmp/foo'

In [56]: os.path.join(os.getcwd(), '/foo/bar')
Out[56]: '/foo/bar'
like image 76
unutbu Avatar answered Oct 11 '22 14:10

unutbu


Think you're writing a utility like cd to check the new directory, you would use

os.path.join(currdir, newdir)

If the user enters /b you would except it to throw the first argument. This hold for plenty of thing using current directory.

like image 31
Dani Avatar answered Oct 11 '22 12:10

Dani