How to find the real user home directory using python?
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 tried, 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,
user It takes you to home directory of current user. On windows have no idea. – mAm Apr 19 ’10 at 16:06
9 Answers 9
On Unix and Windows, return the argument with an initial component of
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.
How to get Desktop location?
I’m using Python on Windows and I want a part of my script to copy a file from a certain directory (I know its path) to the Desktop.
While txtName is the txt File’s name (with full path).
I get the error:
I want the script to work on any computer.
7 Answers 7
You can use os.environ[«HOMEPATH»] to get the path. Right now it’s literally trying to find %HOMEPATH%/Desktop without substituting the actual path.
Maybe something like:
/Desktop») works on Linux and Windows – dashesy Apr 26 ’18 at 3:36
On Unix or Linux:
and to add in your command:
/Desktop») – dashesy Apr 26 ’18 at 3:36
This works on both Windows and Linux:
\\Desktop») – Sabrina Jan 3 ’19 at 14:37
For 3.5+ you can use pathlib:
I can not comment yet, but solutions based on joining location to a user path with ‘Desktop’ have limited appliance because Desktop could and often is being remapped to a non-system drive. To get real location a windows registry should be used. or special functions via ctypes like https://stackoverflow.com/a/626927/7273599
All those answers are intrinsecally wrong : they only work for english sessions.
You should check the XDG directories instead of supposing it’s always ‘Desktop’ .