Search code examples
python-3.xos.path

os.path.join() does not work properly if try to join same folder names. How to fix it?


The code is as follows.

import os

path_1 = "/folder/data"
path_2 = "/folder/media"

print(os.path.join(path_1, path_2))

The output is as follows.

/folder/media

How to get the output properly like this.

/folder/data/folder/media

I want the solution for programs that depend on different operating systems. Therefore adding variables (path_1 + '/' + path_2) is not suitable for this.


Solution

  • From the docs:

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

    So, what you should do is remove the first slash in the second path:

    import os
    
    path_1 = "/folder/data"
    path_2 = "folder/media"    # <- removed first slash
    
    print(os.path.join(path_1, path_2))    # <- prints /folder/data/folder/media