James Tauber

journeyman of some

blog > 2005 > 05 > 24 >

Testing For Directories Outside the Tree

In Leonardo, I have a case where I am concatenating a fixed directory x and a relative path y.

I want to avoid the result being outside the directory tree rooted by x.

Any ideas?

Is

root = os.path.abspath(x) path = os.path.abspath(os.path.join(x, y)) assert path.startswith(root)

a reasonable approach?

Actually, I should clarify: y isn't a relative path as such. y can be '/' which should taken to mean x. So perhaps what I want is:

root = os.path.abspath(x) path = os.path.abspath(os.path.normpath(x + os.sep + y)) assert path.startswith(root)

I ruled out

assert os.path.normpath(x + os.sep + y).startswith(x)

For the case where 'x' is itself relative.

Categories:
prev « python » next

Comments (2)

Ian Bicking on May 24, 2005:

how about os.path.abspath(os.path.join(x, os.path.normpath(y)[1:]))

James Tauber on May 24, 2005:

os.path.normpath(y)[1:] won't work as y doesn't always start with slash. However, os.path.normpath(y).lstrip("/") would do the trick, I think.

Think of it as a chroot to x and then a cd to y. So "/foo" and "foo" have the same effect as values for y.

Created: May 24, 2005
Last Modified: May 24, 2005
Author: James Tauber