我有一堆文件路径,例如:
path1 = "./base/folder1/subfolder"
path2 = "./base/folder2/"
我试图写一个函数,可以给我路径之间的相对差异.使用上面的路径:
>>> get_path_difference(path1, path2)
"../../folder2"
>>> get_path_difference(path2, path1)
"../folder1/subfolder"
我看过os.path模块,因为这似乎很常见,但是我不知道该术语还是不存在.
解决方法:
您可以使用os.path.relpath
:
>>> path1 = "./base/folder1/subfolder"
>>> path2 = "./base/folder2/"
>>> import os
>>> os.path.relpath(path1, path2)
'../folder1/subfolder'
>>> os.path.relpath(path2, path1)
'../../folder2'