989
votes

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?

3
This is marked a duplicate of How to find the real user home directory using python, but I voted to reopen because this answer works on Python 3 and the older answer does not.Dour High Arch
The question title should be improved to ask "What is the correct cross-platform way to get the home directory in Python?"Rich Lysakowski PhD

3 Answers

1779
votes

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())
8
votes

I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

Code:

import os
print(os.path.expanduser("~"))

Output Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

Output Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

I also tested it on Python 2.7.17 and that works too.

3
votes

I found that pathlib module also supports this.

from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')