Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the relative path between two directories?

Tags:

python

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?

like image 992
vmonteco Avatar asked Jun 14 '15 08:06

vmonteco


People also ask

How do you find the relative path?

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.

How do I find the relative path of a directory in Linux?

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 “/”.

What is a relative directory path?

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.

What is a relative path in command prompt?

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.


1 Answers

os.path.relpath(path1, path2) # that's it

like image 161
dlask Avatar answered Oct 06 '22 17:10

dlask