I want to write a script that receives a path to a directory and a path to a file contained in that directory (possibly nested many directories deep) and returns a path to this file relative to the outer directory.
For example, if the outer directory is /home/hugomg/foo
and the inner file is /home/hugomg/foo/bar/baz/unicorns.txt
I would like the script to output bar/baz/unicorns.txt
.
Right now I am doing it using realpath
and string manipulation:
import os
dir_path = "/home/hugomg/foo"
file_path = "/home/hugomg/foo/bar/baz/unicorns.py"
dir_path = os.path.realpath(dir_path)
file_path = os.path.realpath(file_path)
if not file_path.startswith(dir_path):
print("file is not inside the directory")
exit(1)
output = file_path[len(dir_path):]
output = output.lstrip("/")
print(output)
But is there a more robust way to do this? I'm not confident that my current solution is the right way to do this. Is using startswith together with realpath a correct way to test that one file is inside another? And is there a way to avoid that awkward situation with the leading slash that I might need to remove?