7

Situation: I need to find the top level [root] directory of any operating system using the most Pythonic way possible, without system calls.

Problem: While I can check for the operating system using things like if "Windows" in platform.system(), I cannot be too sure if the drive letter is always C:\ or / (the latter being unlikely). I also cannot possibly be sure that there are only Windows and *NIXes that needs to be catalog.

Question: Is there a way to get the top level directory of any operating system? Preferably using the os module since I am already using it.

Timothy Wong
  • 689
  • 3
  • 9
  • 28

3 Answers3

12

I believe os.path.abspath(os.sep) is close to what you are asking for.

DYZ
  • 55,249
  • 10
  • 64
  • 93
  • 3
    This is probably true for all *popular* systems but if you want real portability, the code should also work on systems where this is not true. I vaguely believe VMS is different, for example. – tripleee Jan 19 '18 at 04:55
  • 4
    @tripleee And what would be your proactive, positive suggestion with respect to all other Systems (*having already offered your well-meaning criticism*)....? This Answer also clearly indicates to wit: ***i believe...*** **IS CLOSE TO** ***what you are looking for.*** – Poiz Jan 19 '18 at 05:03
  • 1
    If I had an answer I would post it as an answer. Do you find it problematic that I point out possible flaws for others who discover this answer and wonder whether it is good enough for their needs? – tripleee Jan 19 '18 at 05:30
5

Windows doesn't have a single filesystem root. The best you can do portably is to get the root of the filesystem's current directory (assuming the current directory is called '.').

The expression to get that value is:

os.path.abspath('.').split(os.path.sep)[0]+os.path.sep

On Windows, if the current directory is anywhere under C:, that line will return 'C:\', while unix-like systems will return '/'.

I have no idea what VMS would give you.

cco
  • 5,873
  • 1
  • 16
  • 21
2

You can use the following to get to the root directory.

file_path = os.path.abspath(__file__)
BASE_DIR = os.path.dirname(file_path)
while (os.path.isdir(BASE_DIR)):
    if (BASE_DIR==os.path.dirname(BASE_DIR)):
        break
    else:
        BASE_DIR=os.path.dirname(BASE_DIR)
        
print(f"{BASE_DIR} is the root directory")

First, BASE_DIR is obtained as the current working directory. Then, a while loop is used to go to the parent directory till it reaches the root directory. When BASE_DIR is the root directory, again using os.path.dirname on the root directory gives the root directory itself. So, using that as a check, we can get the root directory.

Vijay
  • 21
  • 3