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

前端 未结 4 546
遥遥无期
遥遥无期 2020-12-30 18:49

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

相关标签:
4条回答
  • 2020-12-30 19:06

    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

    0 讨论(0)
  • 2020-12-30 19:11

    Using pathlib (Python 3.4+):

    import sys
    from pathlib import Path
    
    path = Path(sys.executable)
    root_or_drive = path.root or path.drive
    
    0 讨论(0)
  • 2020-12-30 19:19

    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
    
    0 讨论(0)
  • 2020-12-30 19:21

    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')
    
    0 讨论(0)
提交回复
热议问题