I have two paths.
path1 = /users/fida/data_lake/data/archived/09142023
path2 = /users/fida/data_lake/data/localpublished/SPTTES/End_to_End_Edit_Schedule/2022-08-03_11_22_03.kp
Output Im trying to get after combining both path is:
/users/fida/data_lake/data/archived/09142023/localpublished/SPTTES/End_to_End_Edit_Schedule/2022-08-03_11_22_03.kp
I have tried os.path.relpath but I get dots in the prefix which mess the path.
..\..\localpublished\SPTTES\End_to_End_Edit_Schedule\2022-08-03_11_22_03.kp
Removing the "back dots" can be done by using the second parameter of
os.path.relpath. It defaults toos.curdir, therefore you get the "back dots".You could use
os.path.commonpath(introduced in Python 3.5) to determine the common parent path.Next, you leverage the second argument of
os.path.relpathto get the relative path ofpath2at the common parent path.And finally, you join
path1with the relative path ofpath2usingos.path.join.If you prefer to use
pathlib, then you could also leverage Jean-François T'scommon_parentfunction.pathlib.Path.relative_tois the equivalent ofos.path.relpath. Joining the paths is done by simply using a slash (/).new_pathis apathlib.Pathobject here and can be parsed to a string usingstr().Note:
path2was shortened in both example to avoid horizontal scrolling on StackOverflow.