how to determine whether pathname1 is below bathname2

G

Gelonida

Hi,

I wanted to figure out whether a given path name is below another path name.

Surprisingly this turned out to be more difficult than initially
anticipated:

Let's assume I want to find out, whether path1 is below path2


First I thought about checking whether
path1 starts with path2

For this I had to
- convert path1 / path2 to absolute paths
- I had to normalize the path name

Further this would still fail for
path1='/tmp/dir11' and path2='/tmp/dir1'


next option would be to split both absolute and normalized
paths by os.sep and check whether the path2's split list
starts with path1's split list.

That should work but is also not really nice.


finally I came up with:

#################################################
import os
def is_below_dir(fname,topdir):
relpath = os.path.relpath(fname,topdir)
return not relpath.startswith('..'+os.sep)

print is_below_dir(path1,path2)
#################################################
The basic idea is, if the path name of path1
relative to path2 does NOT start with '..', then
it must be below path2


Does anybody see pitfalls with that solution?
Is there by any chance a function, that I overlooked,
which does already what I'd like to do?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top