Matthew Fournier Matthew Fournier - 6 months ago 20
Python Question

Python: Make an absolute path relative to another path

Suppose I have two file paths as strings in Python, as an example, let's say they are these two:


Is there a way, using the os module, to generate a relative URL based off of the first one? For example, feeding the two above to produce:


I realize this is possible with string manipulation, by splitting off the files at the ends and cutting the first string out of the second, but is there a more robust way, probably using the python

Val Val

Thanks to MPlanchard in the comment below, here is the full answer:

import os

string1 = "C:/Users/testUser/Program/"
string2 = "C:/Users/testUser/Program/data/somefile.txt"

os.path.relpath(string2, os.path.dirname(string1))