What is the correct cross-platform way to get the home directory in Python?
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 expanduser
home = expanduser(~)
If youre on Python 3.5+ you can use pathlib.Path.home():
from pathlib import Path
home = str(Path.home())
I found that pathlib module also supports this.
from pathlib import Path
>>> Path.home()
WindowsPath(C:/Users/XXX)
What is the correct cross-platform way to get the home directory in Python?
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:UsersmXXXXX
Output Linux (Ubuntu):
[email protected]:/mnt/c/Python$ python3 test.py
/home/rxxx
I also tested it on Python 2.7.17 and that works too.