Join two absolute paths?

masky007 Source

How do i join two absolute paths in Python?

e.g.

path1 = 'C:/folder1/folder2/'
path2 = 'D:/directory1/directory2/'

The desired result is: C:/folder1/folder2/directory1/directory2/

I tried os.path.join but it neglects the first path because it detects it's an absolute path. So what's the best way to join paths like this in Python?

Thank you!

python

Answers

answered 4 months ago Jean-Fran├žois Fabre #1

On Windows, I would use os.path.splitdrive combined with a strip of the separator

import os

path1 = 'C:/folder1/folder2/'
path2 = 'D:/directory1/directory2/'

seps = os.sep+os.altsep if os.altsep else os.sep
path3 = os.path.join(path1,os.path.splitdrive(path2)[1].lstrip(seps))  # handles / and \ as separators on windows

print(path3)

result:

C:/folder1/folder2/directory1/directory2/

(if the second path is a relative path, it also works)

The seps = os.sep+os.altsep if os.altsep else os.sep line allows to be compatible with systems with no alternate separators (Linux). This solution works on Windows & Linux, os.splitdrive is a dummy on Linux (returning a tuple with empty first element)

answered 4 months ago Aran-Fey #2

Use the pathlib module to make the 2nd path relative and join it with the first one:

from pathlib import Path

path1 = Path('C:/folder1/folder2/')
path2 = Path('D:/directory1/directory2/')

path3 = path1 / path2.relative_to(path2.anchor)
# result: C:\folder1\folder2\directory1\directory2

To visualize what's happening, let's look at some intermediate output.

Path.anchor gives you the drive letter (or / on linux) of an absolute path. If the path is relative, it returns the empty string:

>>> path2.anchor
'D:\\'
>>> Path('foo').anchor
''

We can use this with Path.relative_to to turn path2 into a relative path. If it was already relative, it won't be affected by this operation:

>>> path2.relative_to(path2.anchor)
WindowsPath('directory1/directory2')
>>> Path('foo').relative_to('')
WindowsPath('foo')

Finally, now that we have a relative path, it can trivially be combined with path1 with the / operator.

comments powered by Disqus