Python,获取当前login用户的Windows特殊文件夹

我如何从我的Python脚本中获取Windows文件夹,如My Documents,Desktop等? 我需要win32扩展吗?

它必须在Windows 2000到Windows 7上工作。

你可以用pywin32扩展来完成它:

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) 

检查shellcon.CSIDL_xxx其他可能的文件夹。

我认为使用pywin32是最好的方法。 否则,你将不得不使用ctypes以某种方式访问SHGetFolderPath函数(其他解决scheme可能是可能的,但这些是我所知道的)。

如果你希望没有win32扩展,你可以使用ctypes来调用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' 

试试winshell (完全是为了这个目的):

 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 () 
 import win32com.client oShell = win32com.client.Dispatch("Wscript.Shell") print oShell.SpecialFolders("Desktop")