How to find the real user home directory using python? How to find the real user home directory using python? python python

How to find the real user home directory using python?


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')


from pathlib import Pathstr(Path.home())

works in Python 3.5 and above. Path.home() returns a Path object providing an API I find very useful.


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, pwdpwd.getpwuid(os.getuid()).pw_dir