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

PythonPathOperating SystemCross Platform

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

Using pathlib (Python 3.4+):

import sys
from pathlib import Path

path = Path(sys.executable)
root_or_drive = path.root or path.drive

Solution 5 - Python

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.

Solution 6 - Python

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 )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBentley4View Question on Stackoverflow
Solution 1 - Pythonuser2743490View Answer on Stackoverflow
Solution 2 - PythonjterraceView Answer on Stackoverflow
Solution 3 - PythonbehnamView Answer on Stackoverflow
Solution 4 - PythonEugene YarmashView Answer on Stackoverflow
Solution 5 - PythonjulianbetzView Answer on Stackoverflow
Solution 6 - PythonBuvinJView Answer on Stackoverflow