Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct cross-platform way 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 ?

like image 738
Nathan Osman Avatar asked Oct 26 '10 23:10

Nathan Osman


People also ask

How do you get to the home directory in Python?

expanduser('~') to get the home directory in Python. This also works if it is a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged. This function is recommended because it works on both Unix and Windows.

Which method is used to find the present working directory of Python in a computer?

The os. getcwd() method is used for getting the Current Working Directory in Python. The absolute path to the current working directory is returned in a string by this function of the Python OS module.

What is Python directory path?

'C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32' Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python. To get it as a bytes object, we use the method getcwdb(). >>> os.


2 Answers

You want to use os.path.expanduser.
This will ensure it works on all platforms:

from os.path import expanduser home = expanduser("~") 

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path home = str(Path.home()) 
like image 138
dcolish Avatar answered Oct 17 '22 11:10

dcolish


I found that pathlib module also supports this.

from pathlib import Path >>> Path.home() WindowsPath('C:/Users/XXX') 
like image 33
Jaeyoon Jeong Avatar answered Oct 17 '22 10:10

Jaeyoon Jeong