Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a directory is a (file system) root

Tags:

python

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?

like image 633
Philippe Avatar asked Mar 22 '12 13:03

Philippe


People also ask

How do I find the root directory of a file?

Type “echo %SYSTEMROOT%" at the command prompt and press “Enter.” The result of this search is the root folder for Microsoft Windows.

How do you check if it is a file or directory?

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.

How do you check if it is a file or directory in Python?

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.


2 Answers

if os.path.dirname(path) == path:
    # you have yourself root.
    # works on Windows and *nix paths.
    # does NOT work on Windows shares (\\server\share)
like image 75
ddotsenko Avatar answered Oct 19 '22 23:10

ddotsenko


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('/..')
'/'
like image 39
FatalError Avatar answered Oct 20 '22 00:10

FatalError