Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Python by (1.6k points)
edited by

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?

1 Answer

0 votes
by (10.9k points)
edited by

@Selena, I will recommend 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() which returns a new path object having the user’s home directory.

from pathlib import Path

Home_address = str(Path.home())

Browse Categories

...