Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

%USERPROFILE% env variable for python

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.

like image 492
Verax Avatar asked Jul 23 '16 17:07

Verax


2 Answers

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)

like image 76
jedwards Avatar answered Oct 07 '22 23:10

jedwards


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

like image 21
Magnus Avatar answered Oct 07 '22 22:10

Magnus