%USERPROFILE% env variable for python

Verax picture Verax · Jul 23, 2016 · Viewed 14.6k times · Source

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.

Answer

jedwards picture jedwards · Jul 23, 2016

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)