How to find the real user home directory using python?

45,195

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 module pwd. 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?

Share:
45,195

Related videos on Youtube

asdfg
Author by

asdfg

Python Newbie

Updated on January 24, 2022

Comments

  • asdfg
    asdfg over 2 years

    I see that if we change the HOME (linux) or USERPROFILE (windows) environmental variable and run a python script, it returns the new value as the user home when I try

    os.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.html

    edit:
    One way to find windows home using pywin32,

    from win32com.shell import shell,shellcon
    home = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, None, 0)
    
    • mAm
      mAm about 14 years
      You 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
      Dour High Arch almost 4 years
      This 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
    ring bearer about 14 years
    But that would only be Unix(Linux) isn't it?
  • Jakob Borg
    Jakob Borg about 14 years
    True, 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
    amphetamachine about 14 years
    Except on Cygwin, in which case both are usually defined, and many times different.
  • Jakob Borg
    Jakob Borg about 14 years
    @ring - yep. Added text to that effect.
  • Felix Kling
    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
    asdfg about 14 years
    This is working in Linux, But not in windows. In windows it just joins the "C:\Documents and settings" to the username passed.
  • endolith
    endolith about 12 years
    This doesn't solve the problem of the "HOME" variable being wrong. See cadence.com/Community/forums/t/17969.aspx for example
  • Jon Coombs
    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
    user1071847 almost 8 years
    This 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
    Reishin over 7 years
    at least this not works on win10 coz varible has name HOMEPATH
  • Julius Kunze
    Julius Kunze over 7 years
    Internally, 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.
    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
    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
    Andrei Korostelev almost 7 years
    This 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
    PascalVKooten over 6 years
    This doesn't work the way you want it (the code at least).
  • Thomas Fauskanger
    Thomas Fauskanger over 6 years
    I know you said Mac and Linux, but on Windows _USERNAME was None. For future readers.
  • PlacidLush
    PlacidLush over 5 years
    pathlib 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
    mikey almost 5 years
    from 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
    PascalVKooten over 4 years
    Would it be an improvement to make it work with windows is to add or "" ?
  • gerrit
    gerrit over 4 years
    translated how?
  • Axel Schneider
    Axel Schneider over 4 years
    Translated to the OS language.
  • AdamE
    AdamE over 2 years
    using 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 the SUDO_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!