Problem
I need to know where the current logged-on user’s home directory is located. On Linux, I’m now using the following:
os.getenv("HOME")
On Windows, however, this does not function. What is the best method to achieve this across platforms?
Asked by Nathan Osman
Solution #1
os.path.expanduser is what you want to utilise. This ensures that it works across all platforms:
from os.path import expanduser
home = expanduser("~")
You can use pathlib.Path.home() if you’re using Python 3.5+:
from pathlib import Path
home = str(Path.home())
Answered by dcolish
Solution #2
This is also supported by the pathlib module, which I discovered.
from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')
Answered by Jaeyoon Jeong
Solution #3
I realize this is an old thread, but I recently required this information for a large-scale project (Python 3.8). Because it has to work on any mainstream OS, I opted with the method suggested by @Max in the comments.
Code:
import os
print(os.path.expanduser("~"))
Output Windows:
PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX
Output Linux (Ubuntu):
rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx
I also tested it on Python 2.7.17, and it works there as well.
Answered by user56700
Solution #4
Although this doesn’t really fit the query (it’s categorized as cross-platform), it might be beneficial to someone.
What is the best way to acquire the home directory for a productive user? (Linux specific).
Assume you’re building an installer script or another solution that necessitates you doing certain operations under the control of specific local users. Changing the effective user in your installer script is the most likely way to do it, although os.path.expanduser(“”) will still return /root.
The desired user name must be included in the argument:
os.path.expanduser(f"~{USERNAME}/")
Note that the above works great without changing EUID, however if the scenario stated above applies, the following example explains how to use it:
import os
import pwd
import grp
class Identity():
def __init__(self, user: str, group: str = None):
self.uid = pwd.getpwnam(user).pw_uid
if not group:
self.gid = pwd.getpwnam(user).pw_gid
else:
self.gid = grp.getgrnam(group).gr_gid
def __enter__(self):
self.original_uid = os.getuid()
self.original_gid = os.getgid()
os.setegid(self.uid)
os.seteuid(self.gid)
def __exit__(self, type, value, traceback):
os.seteuid(self.original_uid)
os.setegid(self.original_gid)
if __name__ == '__main__':
with Identity("hedy", "lamarr"):
homedir = os.path.expanduser(f"~{pwd.getpwuid(os.geteuid())[0]}/")
with open(os.path.join(homedir, "install.log"), "w") as file:
file.write("Your home directory contents have been altered")
Answered by Tammi
Post is based on https://stackoverflow.com/questions/4028904/what-is-the-correct-cross-platform-way-to-get-the-home-directory-in-python