Python 查找文件路径之间的差异
Python find difference between file paths
我有一堆文件路径,比如:
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'
你想要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'
>>>
我有一堆文件路径,比如:
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'
你想要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'
>>>