How can I get Windows special folders like My Documents, Desktop, etc. from my Python script? Do I need win32 extensions?
It must work on Windows 2000 to Windows 7.<
A little bit hacky, but without the need of a special import
import os
os.popen('echo %appdata%').read().strip()
You can do it with the pywin32 extensions:
from win32com.shell import shell, shellcon
print shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, None, 0)
# prints something like C:\Documents and Settings\Username\My Documents\My Pictures
# (Unicode object)
Check shellcon.CSIDL_xxx
for other possible folders.
I think using pywin32 is the best way. Else you'd have to use ctypes
to access the SHGetFolderPath
function somehow (other solutions might be possible but these are the ones I know).
Should you wish to do it without the win32 extensions, you can use ctypes
to call SHGetFolderPath:
>>> import ctypes.wintypes
>>> CSIDL_PERSONAL= 5 # My Documents
>>> SHGFP_TYPE_CURRENT= 0 # Want current, not default value
>>> buf= ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
>>> ctypes.windll.shell32.SHGetFolderPathW(0, CSIDL_PERSONAL, 0, SHGFP_TYPE_CURRENT, buf)
0
>>> buf.value
u'C:\\Documents and Settings\\User\\My Documents'
import win32com.client
oShell = win32com.client.Dispatch("Wscript.Shell")
print oShell.SpecialFolders("Desktop")
Try winshell (made exactly for this purpose):
import winshell
print 'Desktop =>', winshell.desktop ()
print 'Common Desktop =>', winshell.desktop (1)
print 'Application Data =>', winshell.application_data ()
print 'Common Application Data =>', winshell.application_data (1)
print 'Bookmarks =>', winshell.bookmarks ()
print 'Common Bookmarks =>', winshell.bookmarks (1)
print 'Start Menu =>', winshell.start_menu ()
print 'Common Start Menu =>', winshell.start_menu (1)
print 'Programs =>', winshell.programs ()
print 'Common Programs =>', winshell.programs (1)
print 'Startup =>', winshell.startup ()
print 'Common Startup =>', winshell.startup (1)
print 'My Documents =>', winshell.my_documents ()
print 'Recent =>', winshell.recent ()
print 'SendTo =>', winshell.sendto ()