windows Python,获取当前登录用户的windows特殊文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3858851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, get windows special folders for currently logged-in user
提问by Primoz
How can I get Windows special folders like My Documents, Desktop, etc. from my Python script? Do I need win32 extensions?
如何从 Python 脚本中获取 Windows 特殊文件夹,例如我的文档、桌面等?我需要 win32 扩展吗?
It must work on Windows 2000 to Windows 7.
它必须适用于 Windows 2000 到 Windows 7。
回答by AndiDog
You can do it with the pywin32 extensions:
您可以使用 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)
Check shellcon.CSIDL_xxx
for other possible folders.
检查shellcon.CSIDL_xxx
其他可能的文件夹。
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).
我认为使用 pywin32 是最好的方法。否则,您必须使用某种方式ctypes
来访问该SHGetFolderPath
功能(其他解决方案也是可能的,但这些是我所知道的)。
回答by bobince
Should you wish to do it without the win32 extensions, you can use ctypes
to call SHGetFolderPath:
如果您希望在没有 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'
回答by ChristopheD
Try winshell(made exactly for this purpose):
尝试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 ()
回答by Don
import win32com.client
oShell = win32com.client.Dispatch("Wscript.Shell")
print oShell.SpecialFolders("Desktop")
回答by Kipi
A little bit hacky, but without the need of a special import
有点hacky,但不需要特殊导入
import os
os.popen('echo %appdata%').read().strip()