How to get the home directory in Python?
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?
I will recommend to use os.path.expanduser(path) which works on both Unix and Windows,it returns the argument with an initial component of (tilt) ~ or ~user replaced by user’s home address.
Ex-
from os.path import expanduser
home_address = expanduser("~")
For Python 3.5 or more,you can use pathlib.Path.home() for python get home directory.
from pathlib import Path
Home_address = str(Path.home())