Search code examples
pythonfilepath

How to make an absolute path relative to another?


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

C:/Users/testUser/Program/main.py
C:/Users/testUser/Program/data/somefile.txt

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:

data/somefile.txt

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 os module?


Solution

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

    import os
    
    string1 = "C:/Users/testUser/Program/main.py"
    string2 = "C:/Users/testUser/Program/data/somefile.txt"
    
    os.path.relpath(string2, os.path.dirname(string1))