How do you find the root directory so that a path works across multiple computers?

path, python, python-2.7, windows

Solution

Under Windows, there are several pre-defined environment variables that you can look at. One of those is `USERNAME`.

So:

import os
user_name = os.getenv("USERNAME")

Windows also defines environment variables for some directories. If your file should be stored in the user's personal home directory (on Windows 7, this is: `%SystemDrive%\Users\{username}`) you can use `USERDATA` or `USERPROFILE`. This is better than trying to build your own path with the user name.

@Matteo Italia pointed out that `APPDATA` is probably the best one to use; that is specifically a directory for applications to store their data files. This makes sense to me; I think he is right.

So:

import os
appdata_dir_name = os.getenv("APPDATA")

I found a list of Windows environment variables in Wikipedia:

http://en.wikipedia.org/wiki/Environment_variable#Examples_from_Microsoft_Windows

Problem

I am writing a program that sets up a file path that I use to store data. The format is as follows ``` c://users/username/.../endingpath ``` When i switch computers the username is changed. Is there a way or a method that specifies what the username is for the specific computer I am working on? Or is there an even better way of making the path computer independent? I'm running Python 2.7 on Windows 7

Original source