I have a bunch of file paths, such as:
path1 = "./base/folder1/subfolder"
path2 = "./base/folder2/"
I am trying to write a function that can give me the relative difference between the paths. Using the paths above:
>>> get_path_difference(path1, path2)
"../../folder2"
>>> get_path_difference(path2, path1)
"../folder1/subfolder"
I've had a look through the os.path
module, since it seems like this should be a common thing, but either I don't know the terminology or it isn't there.
You can use 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'
You want 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'
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.