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 ?
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.
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.
'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.
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())
I found that pathlib module also supports this.
from pathlib import Path >>> Path.home() WindowsPath('C:/Users/XXX')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With