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

cross-platform, home-directory, python

Solution

You want to use os.path.expanduser. This will ensure it works on all platforms:

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

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())

But it's usually better not to convert `Path.home()` to string. It's more natural to use this way:

with open(Path.home() / ".ssh" / "known_hosts") as f:
    lines = f.readlines()

Problem

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 ?

Original source

Related problems