A system independent way using python to get the root directory/drive on which python is installed

Question:

For Linux this would give me /, for Windows on the C drive that would give me C:\. Note that python is not necessarily installed on the C drive on windows.

Asked By: Bentley4

||

Answers:

You can get the path to the Python executable using sys.executable:

>>> import sys
>>> import os
>>> sys.executable
'/usr/bin/python'

Then, for Windows, the drive letter will be the first part of splitdrive:

>>> os.path.splitdrive(sys.executable)
('', '/usr/bin/python')
Answered By: jterrace

Here’s what you need:

import sys, os

def get_sys_exec_root_or_drive():
    path = sys.executable
    while os.path.split(path)[1]:
        path = os.path.split(path)[0]
    return path
Answered By: behnam

Try this:

import os

def root_path():
    return os.path.abspath(os.sep)

On Linux this returns /

On Windows this returns C:\ or whatever the current drive is

Answered By: user2743490

Using pathlib (Python 3.4+):

import sys
from pathlib import Path

path = Path(sys.executable)
root_or_drive = path.root or path.drive
Answered By: Eugene Yarmash

Based on the answer by Eugene Yarmash, you can use the PurePath.anchor property in pathlib as early as Python >= 3.4, which is:

The concatenation of the drive and root

Using sys.executable to get the location of your python installation, a complete solution would be:

import sys
from pathlib import Path

root = Path(sys.executable).anchor

This results in '/' on POSIX (Linux, Mac OS) and should give you 'c:\' on Windows (assuming your installation is on c:). You can use any other path instead of sys.executable to get the drive and root where this other path is located.

Answered By: julianbetz

Here’s a cross platform, PY2/3 compatible function that returns the root for a given path. Based on your context, you can feed the python executable path into it, the path where the script resides, or whatever makes sense for your use case.

import os

def rootpath( path ):     
    return os.path.splitdrive(os.path.abspath( path ))[0] + os.sep
    

So for the root path of the Python interpreter:

import sys

PY_ROOT_PATH = rootpath( sys.executable )
Answered By: BuvinJ