15

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.

Diego V
  • 6,189
  • 7
  • 40
  • 45
Verax
  • 161
  • 1
  • 1
  • 6
  • You can access environment variables via the [`os.environ` mapping](https://docs.python.org/2/library/os.html#os.environ): `import os; print(os.environ['USERPROFILE'])` – jedwards Jul 23 '16 at 17:33
  • 1
    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.) – Harry Johnston Jul 25 '16 at 00:09

2 Answers2

28

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)

101
  • 8,514
  • 6
  • 43
  • 69
jedwards
  • 29,432
  • 3
  • 65
  • 92
5

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Magnus
  • 59
  • 6