getting user's home directory on windows

K.S.Sreeram sreeram at tachyontech.net
Tue Jul 18 11:30:04 EDT 2006


Hi everybody,

I'm having trouble using os.path.expanduser('~') on windows. It uses
$HOME or ($HOMEDRIVE+$HOMEPATH), but this doesn't work with windows
machines which are part of a domain. On such machines, the HOME envvar
may not be set at all, and the HOMEPATH envvar may be set to '\\'!!

Here's an implementation of getHomeDir which tries to find the best
possible option. I don't know how this'll behave on older versions of
windows such as win2k or win98. Please let me know if anybody knows a
better way to do this :

def getHomeDir() :
    if sys.platform != 'win32' :
        return os.path.expanduser( '~' )

    def valid(path) :
        if path and os.path.isdir(path) :
            return True
        return False
    def env(name) :
        return os.environ.get( name, '' )

    homeDir = env( 'USERPROFILE' )
    if not valid(homeDir) :
        homeDir = env( 'HOME' )
        if not valid(homeDir) :
            homeDir = '%s%s' % (env('HOMEDRIVE'),env('HOMEPATH'))
            if not valid(homeDir) :
                homeDir = env( 'SYSTEMDRIVE' )
                if homeDir and (not homeDir.endswith('\\')) :
                    homeDir += '\\'
                if not valid(homeDir) :
                    homeDir = 'C:\\'
    return homeDir

[sreeram;]

ps:
A bit of googling around got me this informative post:
http://www.mail-archive.com/bug-cvs@gnu.org/msg05565.html

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 260 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20060718/6f3f998f/attachment.sig>


More information about the Python-list mailing list