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?
join(path, '') will add the trailing slash if it's not already there. You can do os. path. join(path, '', '') or os.
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.
os. path. join returns a string; calling the join method of that calls the regular string join method, which is entirely unrelated.
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.
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).
Just strip the slash
path = os.environ.get("HOMEPATH").lstrip(os.path.sep)
os.path.join('C:\one', path, 'three')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With