To calculate the relative path between two absolute paths using the path
package in Python, you can follow these steps:
path
module from the pathlib
package:from pathlib import Path
Path
objects with the two absolute paths:path1 = Path('/path/to/absolute_dir1')
path2 = Path('/path/to/absolute_dir2')
relative_to
method of the Path
object to calculate the relative path:relative_path = path2.relative_to(path1)
relative_path
as required:print(relative_path)
Keep in mind that the relative_to
method will only work if the second path is located inside the first path. Otherwise, it will raise a ValueError
.