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

Viewed 54917

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.

6 Answers

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.

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 )
Related