[Python] Check if a directory is a (file system) root

Discussão em 'Python' iniciado por Stack, Setembro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I have a script that searches for a directory containing a specific file, starting from the current directory and going up the tree (think of trying to find out where the .git directory sits).

    My method looks like this:

    def getDir(self,cwd):
    path = os.path.abspath(cwd)
    if not os.path.isdir(path):
    raise RuntimeError("getDir should not be run on files")
    if FILE in os.listdir(path):
    return path
    parent = os.path.join(path, os.path.pardir)
    if os.access(parent, os.R_OK) and os.access(parent, os.X_OK):
    return self.getDir(parent)
    else
    return None


    Now the problem with this method is that, if it cannot find the directory, it loops (and eventually stack-overflows) because apparently joining / and .. gives you / again. I tried comparing path with parent or their reprs, but that did not work (they were always distinct). My workaround for now is to include a depth counter in the recursive method and stop at some random maximum threshold.

    My question is thus, is there a reliable cross-platform way to check whether I have reached a root in the file system?

    Continue reading...

Compartilhe esta Página