知道两个文件的绝对路径 我想知道其中一个文件,相对于另外一个文件的相对路径
知道两个文件的绝对路径 我想知道其中一个文件,相对于另外一个文件的相对路径
比如 以下两个文件 a b 的绝对路径
但是我想知道 a 相对于 b的相对路径
a = '/usr/share/pyshared/test/a.py'
b = '/usr/lib/dist/test/a.py
我可以通过计算的方式得出是 ../../../share/pyshared/test/a.py
但现在我想通过代码的方式得到得到出来
求算法,
[解决办法]
如下:
import os
a = '/usr/share/pyshared/test/a.py'
b = '/usr/lib/dist/test/a.py'
print os.path.relpath(a, b)
[解决办法]
函数参考说明:
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.
start defaults to os.curdir.
Availability: Windows, Unix.
New in version 2.6.
http://docs.python.org/2/library/os.path.html
[解决办法]
os.path.relpath(a, os.path.dirname(b))