Python find difference between file paths
Asked Answered
D

2

8

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.

Daw answered 19/3, 2016 at 0:45 Comment(0)
C
11

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'
Canotas answered 19/3, 2016 at 0:50 Comment(2)
So it is there. ThanksDaw
(For some reason you can't mark an answer as accepted until five minutes after posting. So I went and forgot about it.)Daw
B
3

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'
>>> 
Bomber answered 19/3, 2016 at 0:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.