What is the correct cross-platform way to get the home directory in Python?
You want to use os.path.expanduser.
This will ensure it works on all platforms:
from os.path import expanduserhome = expanduser("~")
If you're on Python 3.5+ you can use pathlib.Path.home():
from pathlib import Pathhome = str(Path.home())
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 osprint(os.path.expanduser("~"))
Output Windows:
PS C:\Python> & C:/Python38/python.exe c:/Python/test.pyC:\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.
I found that pathlib module also supports this.
from pathlib import Path>>> Path.home()WindowsPath('C:/Users/XXX')