I have this program in Python which should save text files to a folder inside the "My Documents" of the user. The problem is that the program doesn't know the username, or the Windows version to know the correct path. How could I get this done?
Asked
Active
Viewed 3,721 times
3 Answers
6
The doc says, the following code is expanded to the user's home directory on windows too..
homeDir = os.path.expanduser("~")
From the documentation:
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.
Also look into this for using Win32APIs

Community
- 1
- 1

UltraInstinct
- 43,308
- 12
- 81
- 104
-
@JBernardo: Its actually uses more environment-variables than that. I updated my post with the actual wordings. – UltraInstinct Jun 24 '12 at 03:48
-
this is not the correct solution, but it helps. This gives the Path to the user's home, not the user's My Documents folder – jeanc Jun 26 '12 at 04:15
4
Get from the environment variable:
os.environ['USERPROFILE']
or
os.environ['HOME']

JBernardo
- 32,262
- 10
- 90
- 115
-
On my Windows 10 system, it likes the 'USERPROFILE' version but doesn't like the 'HOME' one and reports an error. The USERPROFILE version returns "C:\Users\
" – Developer63 Aug 30 '21 at 19:27
2
The winpaths package provides functions to retrieve the values you need.

Ned Batchelder
- 364,293
- 75
- 561
- 662