如何从 Python 脚本中获取 Windows 特殊文件夹,如
My Documents
、Desktop
等?我需要 win32 扩展吗?
它必须在 Windows 2000 到 Windows 7 上运行。
如果您希望在没有 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'
您可以使用 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
函数(可能还有其他解决方案,但这些是我所知道的)。
import win32com.client
oShell = win32com.client.Dispatch("Wscript.Shell")
print oShell.SpecialFolders("Desktop")
尝试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 ()
有点 hacky,但不需要特殊导入
import os
os.popen('echo %appdata%').read().strip()
https://pypi.org/project/userpaths这是最好的替代方案。
# Get the user's My Documents folder
导入用户路径 my_docs = userpaths.get_my_documents() 就可以直接使用了。