Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the filesystem's root directory in Python?

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.

like image 862
Timothy Wong Avatar asked Jan 03 '23 22:01

Timothy Wong


2 Answers

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

like image 165
DYZ Avatar answered Jan 11 '23 23:01

DYZ


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.

like image 22
cco Avatar answered Jan 11 '23 23:01

cco