0

I recently started learning Python language and the textbook I have, while presenting the os module, explained how to use the os.name attribute in order to determine the root directory of the operative system - so, a hardcoded solution based on the if-elif-else construct. Just for the sake of practising and start to get keen on this language, I tried to generalise this solution.

I used the os.path.split() function, knowing that splitting the root directory root_dir returns the tuple (root_dir, ''), where the first element is the root directory and the second is the empty string. Here, I used a support variable my_tuple, initialised to (os.getcwd(), None), which is updated via the use of split() function in a while loop until its second element is ''.

my_tuple = (os.getcwd(), None)
while my_tuple[1] != '':
    my_tuple = os.path.split(my_tuple[0])
root_dir = my_tuple[0]

Clearly, this is a clumsy solution, for which reason I was wondering if there's a cleaner - and a more Pythonic - way to achieve the goal. For example, if one imports the pathlib module, they may use the PurePath.root attribute, easy peasy.

Is something similar possible with os module?

lornio
  • 13
  • 4
  • https://stackoverflow.com/questions/12041525/a-system-independent-way-using-python-to-get-the-root-directory-drive-on-which-p describes a few functions which should help. – Pavel Shishpor Feb 22 '22 at 20:47
  • @PavelShishpor exaxtly what I was looking for. Thank you. – lornio Feb 23 '22 at 09:16

1 Answers1

0

The comment to your post contains the solution you're asking for, but I'll write it here for completeness. With the os-module, you can use

path = os.getcwd()
root = os.path.splitdrive(path)[0]

to have the variable root contain what you're after.

eandklahn
  • 537
  • 4
  • 8