%USERPROFILE% env variable for python
Asked Answered
P

2

18

I am writing a script in Python 2.7.

It needs to be able to go whoever the current users profile in Windows.

This is the variable and function I currently have:

import os
desired_paths = os.path.expanduser('HOME'\"My Documents")

I do have doubts that this expanduser will work though. I tried looking for Windows Env Variables to in Python to hopefully find a list and know what to convert it to. Either such tool doesn't exist or I am just not using the right search terms since I am still pretty new and learning.

Psychosexual answered 23/7, 2016 at 17:28 Comment(2)
You can access environment variables via the os.environ mapping: import os; print(os.environ['USERPROFILE'])Medeah
Note that the "My Documents" junction point in the user's profile won't necessarily exist. For example, if a non-English version of Windows is installed, or if the user's documents folder has been moved or redirected. (You might be OK if this is for in-house use only.)Pericope
M
34

You can access environment variables via the os.environ mapping:

import os
print(os.environ['USERPROFILE'])

This will work in Windows. For another OS, you'd need the appropriate environment variable.

Also, the way to concatenate strings in Python is with + signs, so this:

os.path.expanduser('HOME'\"My Documents")
                   ^^^^^^^^^^^^^^^^^^^^^

should probably be something else. But to concatenate paths you should be more careful, and probably want to use something like:

os.sep.join(<your path parts>)
# or
os.path.join(<your path parts>)

(There is a slight distinction between the two)

If you want the My Documents directory of the current user, you might try something like:

docs = os.path.join(os.environ['USERPROFILE'], "My Documents")

Alternatively, using expanduser:

docs = os.path.expanduser(os.sep.join(["~","My Documents"]))

Lastly, to see what environment variables are set, you can do something like:

print(os.environ.keys())

(In reference to finding a list of what environment vars are set)

Medeah answered 23/7, 2016 at 17:37 Comment(0)
H
5

Going by os.path.expanduser , using a ~ would seem more reliable than using 'HOME'.

Hagerty answered 23/7, 2016 at 17:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.