13

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?

SeniorJD
  • 6,946
  • 4
  • 36
  • 53
vmonteco
  • 14,136
  • 15
  • 55
  • 86
  • possible duplicate of [BASH: Convert absolute path into relative path given a current directory](http://stackoverflow.com/questions/2564634/bash-convert-absolute-path-into-relative-path-given-a-current-directory) – fferri Jun 14 '15 at 08:31
  • @mescalinum The answer of this post is a pythonic answer but the question was for bash. – vmonteco Jun 14 '15 at 08:42
  • top answer of [that question](http://stackoverflow.com/questions/2564634/bash-convert-absolute-path-into-relative-path-given-a-current-directory) is in python – fferri Jun 14 '15 at 08:43
  • Yes, that's what I said, but not the question. – vmonteco Jun 14 '15 at 08:46
  • But now there are posts that could be almost the same, I agree. Like this one http://stackoverflow.com/questions/7287996/python-get-relative-path-from-comparing-two-absolute-paths I didn't find before. – vmonteco Jun 14 '15 at 08:48

2 Answers2

17

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

dlask
  • 8,776
  • 1
  • 26
  • 30
3

Just use the relpath() function of the os module.

import os

os.path.relpath(pathA, pathB)

As per the docs,

os.path.relpath(path[, start])

Return a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or start.

Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126