File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 3737#
3838
3939import os
40+ import pathlib
4041
4142def copytree (src , dst , symlinks = False , ignore = None ):
4243 """
@@ -115,6 +116,39 @@ def relpath(path, relative_to=None):
115116 return os .path .abspath (path )
116117
117118
119+ def relpath2 (path , relative_to = None ):
120+ """
121+ Returns the path for the given file or directory relative to the given
122+ directory or, if that would require path traversal, returns the
123+ absolute path.
124+
125+ :param path: Path to find the relative path for
126+ :type path: str or pathlib.Path
127+ :param relative_to: The directory to find the path relative to.
128+ Defaults to the current directory
129+ :type relative_to: str or pathlib.Path
130+
131+ :return:
132+ """
133+
134+ if not isinstance (path , pathlib .Path ):
135+ path = pathlib .Path (path )
136+
137+ abs_path = path .absolute ()
138+
139+ if relative_to is None :
140+ relative_to = pathlib .Path ().absolute ()
141+
142+ if not isinstance (relative_to , pathlib .Path ):
143+ relative_to = pathlib .Path (relative_to )
144+
145+ relative_to = relative_to .absolute ()
146+
147+ try :
148+ return abs_path .relative_to (relative_to )
149+ except ValueError :
150+ return abs_path
151+
118152
119153def delete (filename ):
120154 """
You can’t perform that action at this time.
0 commit comments