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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With