Finding a user’s Documents folder on Windows and Mac

Aug 5, 2005 14:27 · 260 words · 2 minute read

Update: I revised this to include the Mac way of finding the user’s documents directory. Perhaps the Python standard library should include a way to get at the best path for storing documents.

For Windows

Yuck. Coming within 10 feet of win32 programming, you can really appreciate the need for .NET and a sane API.

For anyone needing to find the user’s “My Documents” folder on Windows with Python, here is one way that I’ve found to work based on this MSDN article. (As awful as the API is, I will say that MSDN is a great resource!)

from import shell
df = shell.SHGetDesktopFolder()
pidl = df.ParseDisplayName(0, None,  
mydocs = shell.SHGetPathFromIDList(pidl)

I really wanted to use shell.SHGetFolderPath but I couldn’t get a combination that works for retrieving “My Documents”. In order to get My Documents from there, you need a PyHandle for the user, and I got the method above working before I found my handle… You can get “My Pictures” easily from shell.SHGetFolderPath, however.

from win32com import shell, shellcon
mypict = shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, 0, 0)

I’m sure that if you do win32 programming all the time, you get used to this stuff. Knowing that doesn’t make me feel less sorry for the folks that are doing win32 programming.

For The Mac

The Mac (Carbon) way of doing this is similar to the SHGetFolderPath call on Windows. Both of these APIs make more sense than the one I went with (ParseDisplayName with that lovely GUID).

from Carbon import Folder, Folders
folderref = Folder.FSFindFolder(Folders.kUserDomain, 
    Folders.kDocumentsFolderType, False)
docs = folderref.as_pathname()