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 repr
s, 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?
Type “echo %SYSTEMROOT%" at the command prompt and press “Enter.” The result of this search is the root folder for Microsoft Windows.
File. isDirectory() checks whether a file with the specified abstract path name is a directory or not. This method returns true if the file specified by the abstract path name is a directory and false otherwise.
We use the is_file() function, which is part of the Path class from the pathlib module, or exists() function, which is part of the os. path module, in order to check if a file exists or not in Python.
if os.path.dirname(path) == path:
# you have yourself root.
# works on Windows and *nix paths.
# does NOT work on Windows shares (\\server\share)
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:
>>> os.path.realpath('/usr/bin/..')
'/usr'
>>> os.path.realpath('/usr/bin/../..')
'/'
>>> os.path.realpath('/usr/bin/../../..')
'/'
>>> os.path.realpath('/..')
'/'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With