Python doesn't understand %userprofile%

Tim Golden mail at timgolden.me.uk
Tue Jun 10 12:11:09 EDT 2008


bsagert at gmail.com wrote:
> In xp when I try os.path.getmtime("%userprofile/dir/file%") Python
> bites back with "cannot find the path specified" Since my script has
> to run on machines where the username is unspecified I need a fix.

Well I can see a few problems here. 

First is that putting percent signs around the whole path is 
never going to work anyway. You want something like:

"%USERPROFILE%/dir/file". 

Secondly, the expansion of environment variables like 
USERPROFILE is done for you by the shell or the command 
prompt. You have to do it for yourself if you're opening your 
own files. You want something like:

import os
print os.path.getmtime (os.path.join (os.environ['USERPROFILE'], "ntuser.ini"))

But finally, what do you mean "run on machines where the username is
unspecified"? If you mean: where no user is logged in, then you won't
have a (meaningful) userprofile in any case: it might be the Default User
profile; I'm not sure. But is that what you want?

You *can* use the functions in the win32profile module of the pywin32
packages to find out various things about profiles directories, but things
can get quite complicated if users have roaming profiles and the like.

TJG



More information about the Python-list mailing list