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?
I don’t think you can find out if it’s a file system root portably, however I’d suggest doing a call to
os.path.realpath()on both the current dir and your calculated parent and compare if they’re the same — this means you are spinning your wheels and there’s no point in proceeding.For example: