How to get the home directory in Python?


Question

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?

1
735
7/8/2014 9:30:49 AM

Accepted Answer

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())
1303
10/30/2017 2:17:49 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon