HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
directoryhometheplatformwaywhatcrossget

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 ?

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("~")

Context

Stack Overflow Q#4028904, score: 2167

Revisions (0)

No revisions yet.