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.

The original post was in the category: python but I'm still in the process of migrating categories over.

The original post had 2 comments I'm in the process of migrating over.