Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a path is a subdirectory of another?

Tags:

python

file

I am given a list of paths that I need to check files within. Of course, if I am given a root, and a subdirectory, there is no need to process the sub-directory. For example

c:\test  // process this
c:\test\pics // do not process this
c:\test2 // process this

How can I tell (cross platform) that a path is not a subdirectory of the other. Preferably I would want this to be cross platform, and am not worried about symlinks as long as they are not cyclical (worse case is that I end up processing the data twice).

UPDATE: here is the code I ended up using, thanks to @F.J

   def unique_path_roots(paths):
    visited = set()
    paths = list(set(paths))

    for path in sorted(paths,key=cmp_to_key(locale.strcoll)):
        path = normcase(normpath(realpath(path)))

        head, tail = os.path.split(path)
        while head and tail:
            if head in visited:
                break
            head, tail = os.path.split(head)
        else:
            yield path
            visited.add(path)
like image 627
esac Avatar asked Jan 13 '12 17:01

esac


People also ask

What is the difference between a directory and a subdirectory?

Files are organized by storing related files in the same directory. In a hierarchical file system (that is, one in which files and directories are organized in a manner that resembles a tree), a directory contained inside another directory is called a subdirectory.

Which directory contain a subdirectory in it?

The directory / (root) contains the subdirectories /usr , /bin , /export/home and /lib , among others subdirectories. The subdirectory /export/home contains user1 , user2 , and user3 .

What is the difference between root directory and subdirectory?

Subdirectories may refer to folders located directly within a folder, as well as folders that are stored in other folders within a folder. For example, the main directory of a file system is the root directory. Therefore, all other folders are subdirectories of the root folder.


1 Answers

def is_subdir(path, directory):
    path = os.path.realpath(path)
    directory = os.path.realpath(directory)

    relative = os.path.relpath(path, directory)

    if relative.startswith(os.pardir):
        return False
    else:
        return True
like image 187
jgoeders Avatar answered Oct 22 '22 04:10

jgoeders