How to get the user name, and to show a select directory dialog?

Tim Golden tim.golden at viacom-outdoor.co.uk
Fri May 23 03:51:04 EDT 2003


Joe Francia <usenet at soraia.com> wrote in message news:<3ECD4803.8000700 at soraia.com>...
> Arnal wrote:
> 
> > Hi!
> > 
> > I would like to obtain the name of the current logged user on a Windows
> > machine, so I can get the "My documents" and "Desktop" folders.
> 
> #assumes stand alone win32api or
> #ActiveState's Python installed
> 
> import win32api
> win32api.GetUserName()
> 
> > I want to allow the user to specify the initial directory of the save
> > command, and the open command. The "My documents" would be somehow basic to
> > acceess, but I must have the username in the path (or can I access this
> > folder directly with a function?). Or how to access the user name, else?
> 
> import win32api, os
> 
> MYDOCS = 'My Documents'
> DESKTOP = 'Desktop'
> 
> home_path = win32api.GetEnvironmentVariable('USERPROFILE')
> desktop_path = os.path.join(home_path, DESKTOP)
> doc_path = os.path.join(home_path, MYDOCS)
> 
> > I would like, as well, to show a "select directory dialog". I can already
> > put a select file and put file; I think that selecting a directory must be
> > in the same module, isn't it?
> > 
> 
> Hard to say when you don't mention what GUI toolkit you're using (PyQt, 
> Tkinter, wxPython, direct win32 calls,...).
> 
> jf

Having just had to struggle through this one myself, I'll offer a
solution. There are two aspects to this: getting the name, and getting
the folder.

The first has already been answered (win32api.GetUserName), altho' I
would point out that this won't work on Win9x (try
win32wnet.WNetGetuser instead). The "special" directories, such as
MyDocs, Desktop and so on, are best accessed via the shell functions
which keep track of them even if the system administrator decides to
move them to a network drive etc.

I have a module for these sorts of things of which the following is a
snippet:

<code>

  from win32com.shell import shell, shellcon
  def personal_folder ():
    return shell.SHGetSpecialFolderPath (0, shellcon.CSIDL_PERSONAL)
  my_documents = personal_folder

</code>

If you're interested, I can send you the whole module. It's not
terribly inspiring, but it does the job, and saves me having to
remember which of those blasted constants I need to use to get which
folder.

TJG




More information about the Python-list mailing list