I would like to find the relative path between two directories on my system.
Example:
If I have pathA == <pathA>
and pathB == <pathA>/dir1/dir2
, the relative path between them will be dir1/dir2
.
How could I find it in python? Is there a tool I could use?
If pathB is contained in pathA, I could just do pathB.replace(pathA, '')
to get this relative path, but what if pathB isn't contained in pathA?
A relative path starts with / , ./ or ../ . To get a relative path in Python you first have to find the location of the working directory where the script or module is stored. Then from that location, you get the relative path to the file want.
The Linux relative path the path is defined with the current working directory (for a present relative path, we can use the “pwd” command). There is no need to start the relative path with “/”.
A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.
Relative paths A relative path is calculated relative to your "current working directory" -- the directory you are currently in at a command prompt, as displayed by pwd . This is an example relative path: projects . That path only has meaning given a current working directory.
os.path.relpath(path1, path2) # that's it
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