pythoncross-platformhome-directory

What is a cross-platform way to get the home directory?


I need to get the location of the home directory of the current logged-on user. Currently, I've been using the following on Linux:

os.getenv("HOME")

However, this does not work on Windows. What is the correct cross-platform way to do this ?


Solution

  • On Python 3.5+ you can use pathlib.Path.home():

    from pathlib import Path
    home = Path.home()
    
    # example usage:
    with open(home / ".ssh" / "known_hosts") as f:
        lines = f.readlines()
    

    to get a pathlib.PosixPath object. Use str() to convert to a string if necessary.


    On older Python versions, you can use os.path.expanduser.

    from os.path import expanduser
    home = expanduser("~")