How to get the home directory in Python?

1.6K    Asked by GarethBeacham in Python , Asked on Apr 10, 2021

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?

Answered by Gareth Beacham

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

Your Answer

Interviews

Parent Categories