How to find the real user home directory using python?
Solution 1
I think os.path.expanduser(path)
could be helpful.
On Unix and Windows, return the argument with an initial component of
~
or~user
replaced by that user‘s home directory.On Unix, an initial
~
is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in modulepwd
. An initial~user
is looked up directly in the password directory.On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial
~user
is handled by stripping the last directory component from the created user path derived above.If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.
So you could just do:
os.path.expanduser('~user')
Solution 2
from pathlib import Path
str(Path.home())
works in Python 3.5 and above. Path.home()
returns a Path
object providing an API I find very useful.
Solution 3
I think os.path.expanduser(path)
is the best answer to your question, but there's an alternative that may be worth mentioning in the Unix world: the pwd
package. e.g.
import os, pwd
pwd.getpwuid(os.getuid()).pw_dir
Solution 4
home_folder = os.getenv('HOME')
This should work on Windows and Mac OS too, works well on Linux.
Solution 5
Really, a change in environment variable indicates that the home must be changed. So every program/script should have the new home in context; also the consequences are up to the person who changed it.
I would still stick with
home = os.getenv('USERPROFILE') or os.getenv('HOME')
what exactly is required?
Related videos on Youtube
Comments
-
asdfg over 2 years
I see that if we change the
HOME
(linux) orUSERPROFILE
(windows) environmental variable and run a python script, it returns the new value as the user home when I tryos.environ['HOME'] os.exp
Is there any way to find the real user home directory without relying on the environmental variable?
edit:
Here is a way to find userhome in windows by reading in the registry,
http://mail.python.org/pipermail/python-win32/2008-January/006677.htmledit:
One way to find windows home using pywin32,from win32com.shell import shell,shellcon home = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, None, 0)
-
mAm about 14 yearsYou may want to checkout unix command(shortcut):
~user
It takes you to home directory of current user. On windows have no idea. -
Dour High Arch almost 4 yearsThis should be marked a duplicate of How to get the home directory in Python? since that question's accepted answer works on Python 3 and this question's does not.
-
-
ring bearer about 14 yearsBut that would only be Unix(Linux) isn't it?
-
Jakob Borg about 14 yearsTrue, but changing the environment variable as in the question will "fool" this method as well. Now, why one would want to do that, I can't say. :)
-
amphetamachine about 14 yearsExcept on Cygwin, in which case both are usually defined, and many times different.
-
Jakob Borg about 14 years@ring - yep. Added text to that effect.
-
Felix Kling about 14 years@calmh: Yes, I changed it to use
'~user'
which should work on Linux and Windows (here I am not 100% sure because I don't have Windows to test it ;) ). -
asdfg about 14 yearsThis is working in Linux, But not in windows. In windows it just joins the "C:\Documents and settings" to the username passed.
-
endolith about 12 yearsThis doesn't solve the problem of the "HOME" variable being wrong. See cadence.com/Community/forums/t/17969.aspx for example
-
Jon Coombs over 10 years@asdfg : It sounds to me like it worked correctly. But I too thought it had failed the first time I tried, because at first I was passing the literal string '~user' (which really needs to be something literal such as '~Bob') instead of just '~' (which appends the current user).
-
user1071847 almost 8 yearsThis is useful when you want the home directory of the user, but the HOME environment variable is incorrectly set. As the author noted, it's not platform-independent but is rather for UNIX, not Windows.
-
Reishin over 7 yearsat least this not works on win10 coz varible has name HOMEPATH
-
Julius Kunze over 7 yearsInternally,
pathlib
still relies on environment variables, so this does not answer your specific question. Since the more general questions were all marked as duplicates and refer to here, this might be the best place for this answer. -
s.m. about 7 years@Reishin that's not quite true, I just tested it and it works on Windows 10 Pro. I really don't think they can afford to change the name of an environment variable on a whim, given the amount of software that expects to find it by that name.
-
Reishin about 7 years@s.m. please try to found here technet.microsoft.com/en-us/library/cc749104(v=ws.10).aspx "HOME" variable. If you have custom variable, that not means all ppl have it. In most common, such like mingw, cygwin, git shell, etc...setting it for you. But if you run cmd.exe, you would be surprised
-
Andrei Korostelev almost 7 yearsThis is better than relying on HOME env variable which may or may not be preserved across sudo calls. For example HOME env. variable is set to target's user in Debian 8 ('sudo' acts as 'sudo -H') but is preserved in Ubuntu 16 ('sudo' acts as 'sudo -E')
-
PascalVKooten over 6 yearsThis doesn't work the way you want it (the code at least).
-
Thomas Fauskanger over 6 yearsI know you said Mac and Linux, but on Windows
_USERNAME
wasNone
. For future readers. -
PlacidLush over 5 yearspathlib is my go to library for path handling now! Didn't know about .home(). I will have to revisit the docs again to review all the goodness. Cheers!
-
mikey almost 5 yearsfrom pathlib import Path; Path.home().as_posix() # works in Windows as well. Essentailly the same as Spronck's method, it might be more natural.
-
PascalVKooten over 4 yearsWould it be an improvement to make it work with windows is to add
or ""
? -
gerrit over 4 yearstranslated how?
-
Axel Schneider over 4 yearsTranslated to the OS language.
-
AdamE over 2 yearsusing pathlib Path.home() would be great except for when python is being run as
sudo
on Linux or Mac. Is there a way to get theSUDO_USER
environment variable to get the "original" username using Path.home()? If not, then this post seems like a solution stackoverflow.com/a/42750492/796858. Thanks!