11

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?

Community
  • 1
  • 1
matt wilkie
  • 17,268
  • 24
  • 80
  • 115
  • 5
    I'm sorry that this has bitten you a few times, but it's an *intentional* and documented feature. – Martijn Pieters Feb 20 '13 at 20:41
  • 3
    The docs make it clear this is intentional behaviour, but given that the "mostly pointless" comment I borrowed from the linked answer has been upvoted 14 or more times I'm certainly not alone in thinking there should be an alternative. – matt wilkie Feb 20 '13 at 21:37
  • The alternative, certainly, is to make sure your arguments don't start with a slash. E.g. one line of `args = [a[1:] for a in args if a.startswith('\\') else a]` or something to that effect. I suspect that most people understand how it's supposed to work. Alternatively fix HOMEPATH; on Windows this is intended to be at the fs root but if you're using it in a different way then you should make it look like a relative path rather than an absolute one. – dash-tom-bang Feb 20 '13 at 22:03
  • @mattwilkie: I comment cannot be *downvoted*. I would have done so if I could have. Judging by the question quality of many first-time Python question askers, it won't be hard to find 14 people that misunderstand why `os.path.join()` does this. – Martijn Pieters Feb 21 '13 at 13:51

2 Answers2

9

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

kindall
  • 178,883
  • 35
  • 278
  • 309
5

Just strip the slash

path = os.environ.get("HOMEPATH").lstrip(os.path.sep)
os.path.join('C:\one', path, 'three')
jdi
  • 90,542
  • 19
  • 167
  • 203