How do i join two absolute paths in Python?
path1 = 'C:/folder1/folder2/' path2 = 'D:/directory1/directory2/'
The desired result is:
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?
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).lstrip(seps)) # handles / and \ as separators on windows print(path3)
(if the second path is a relative path, it also works)
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)
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