-1

I want to merge two paths using os.path.join() function. Paths I want to merge are- '/Users/Tushar/Desktop/' and '/Exp'.

I was doing - os.path.join('/Users/Tushar/Desktop','/Exp') and

  • Expected output was - '/Users/Tushar/Desktop/Exp'

  • But I actually got - '/Exp'

Why am I getting this output?

This kind of output is occurring on all systems, macOS, Windows, Linux

I have tried-

  1. os.path.join('/Users/Tushar/Desktop','Exp') and I got the correct output i.e '/Users/Tushar/Desktop/Exp'

  2. os.path.join('/Users/Tushar/Desktop/','Exp') and I got the correct output again i.e '/Users/Tushar/Desktop/Exp'

  3. os.path.join('/Users/Tushar/Desktop','/Exp','/123') gives '/123' but I expected '/Users/Tushar/Desktop/Exp/123'

  4. Apparently os.path.join('/Users/Tushar/Desktop/,'\\Exp') gives the correct output i.e. '/Users/Tushar/Desktop/\\Exp' where as os.path.join('/Users/Tushar/Desktop/','/Exp') gives the incorrect output '/Exp' .

So far, I have got to the point that it has something to do with the slash (/) at the end of '/Exp' which is the cause of this incorrect output.

Tushar
  • 511
  • 5
  • 7
  • Possible duplicate of [Why doesn't os.path.join() work in this case?](https://stackoverflow.com/questions/1945920/why-doesnt-os-path-join-work-in-this-case) – Davis Herring Jun 08 '19 at 19:36

2 Answers2

1

From Python documentation

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

You'll need to manually strip all leading slashes in all components except the first one:

def my_join(root, *args):
    args = [arg.lstrip(os.path.sep) for arg in args]
    return os.path.join(root, *args)

See example:

>>> my_join('/home/ibug', '/oh', '/yeah', '/handsome')
'/home/ibug/oh/yeah/handsome'
iBug
  • 35,554
  • 7
  • 89
  • 134
0

this behavior is exactly as documented

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111