Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

an os.path.join() that doesn't discard before leading slash?

Tags:

python

os.path

Python's os.path.join has been described as "mostly pointless" because it discards any arguments prior to one containing a leading slash. Leaving aside for the moment that this is intentional and documented behaviour, is there a readily available function or code pattern which doesn't discard like this?

Given HOMEPATH=\users\myname, the following will discard the beginning of the path

print os.path.join('C:\one', os.environ.get("HOMEPATH"), 'three')

result:

\Users\myname\three

desired:

C:\one\Users\myname\three

Having been bitten by this a few times, I'm pretty good now at noticing a leading slash when it's something I've written, but what about when when you don't know what the incoming string is looking like, as in this example?

like image 883
matt wilkie Avatar asked Feb 20 '13 20:02

matt wilkie


People also ask

Does os path join add trailing slash?

join(path, '') will add the trailing slash if it's not already there. You can do os. path. join(path, '', '') or os.

What is os path join?

os. path. join combines path names into one complete path. This means that you can merge multiple parts of a path into one, instead of hard-coding every path name manually.

Does os path join return a string?

os. path. join returns a string; calling the join method of that calls the regular string join method, which is entirely unrelated.

Which of the following statement is used to join the path components?

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.


2 Answers

Maybe os.environ.get("HOMEPATH").lstrip(os.path.sep)... it would be trivial to write your own version of join that did this on every argument (or the second and subsequent).

like image 184
kindall Avatar answered Oct 29 '22 17:10

kindall


Just strip the slash

path = os.environ.get("HOMEPATH").lstrip(os.path.sep)
os.path.join('C:\one', path, 'three')
like image 28
jdi Avatar answered Oct 29 '22 17:10

jdi