How can I tell if a file is a descendant of a given directory?

Use os.path.realpath and os.path.commonprefix:

os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == "/the/dir/"

os.path.realpath will expand any symlinks as well as .. in the filename. os.path.commonprefix is a bit fickle -- it doesn't really test for paths, just plain string prefixes, so you should make sure your directory ends in a directory separator. If you don't, it will claim /the/dirtwo/filename is also in /the/dir


Python 3.5 has the useful function os.path.commonpath:

Return the longest common sub-path of each pathname in the sequence paths. Raise ValueError if paths contains both absolute and relative pathnames, or if paths is empty. Unlike commonprefix(), this returns a valid path.

So to check if a file is a descendant of a directory, you could do this:

os.path.commonpath(["/the/dir", os.path.realpath(filename)]) == "/the/dir"

Unlike commonprefix, you don't need to worry if the inputs have trailing slashes or not. The return value of commonprefix always lacks a trailing slash.