Python找到文件路径之间的差异

时间:2016-03-19 00:45:42

标签: python file path filepath difference

我有一堆文件路径,例如:

path1 = "./base/folder1/subfolder"
path2 = "./base/folder2/"

我正在尝试编写一个可以给我路径之间相对差异的函数。使用上面的路径:

>>> get_path_difference(path1, path2)
"../../folder2"
>>> get_path_difference(path2, path1)
"../folder1/subfolder"

我已经浏览了os.path模块,因为看起来这应该是常见的事情,但要么我不知道术语,要么它不存在。

2 个答案:

答案 0 :(得分:4)

您可以使用os.path.relpath

String fullName = "John Erich Daws Black";
int idx = fullName.lastIndexOf(' ');
if (idx == -1)
    throw new IllegalArgumentException("Only a single name: " + fullName);
String firstName = fullName.substring(0, idx);
String lastName  = fullName.substring(idx + 1);

答案 1 :(得分:0)

您想要os.path.relpath

>>> import os
>>>
>>> path1 = "./base/folder1/subfolder"
>>> path2 = "./base/folder2/"
>>>
>>> os.path.relpath(path1, path2)
'../folder1/subfolder'
>>>
>>> os.path.relpath(path2, path1)
'../../folder2'
>>>