Python, get windows special folders for currently logged-in user

我的未来我决定 提交于 2019-11-26 12:17:17

问题


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.


回答1:


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).




回答2:


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'



回答3:


import win32com.client
oShell = win32com.client.Dispatch("Wscript.Shell")
print oShell.SpecialFolders("Desktop")



回答4:


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 ()



回答5:


A little bit hacky, but without the need of a special import

import os
os.popen('echo %appdata%').read().strip()


来源:https://stackoverflow.com/questions/3858851/python-get-windows-special-folders-for-currently-logged-in-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!