正确定位Windows文件夹在Python中有些繁琐。根据答案覆盖微软的开发技术,比如这一次,他们应该使用Vista中获得已知的文件夹API。Python标准库没有包装此API(尽管从2008年开始有一个问题要求它),但是无论如何,都可以使用ctypes模块来访问它。
调整以上答案以使用文件夹ID进行此处所示的下载,并将其与您现有的Unix代码结合使用,应会产生如下所示的代码:
import osif os.name == 'nt': import ctypes from ctypes import windll, wintypes from uuid import UUID # ctypes GUID copied from MSDN sample pre class GUID(ctypes.Structure): _fields_ = [ ("Data1", wintypes.DWORD), ("Data2", wintypes.WORD), ("Data3", wintypes.WORD), ("Data4", wintypes.BYTE * 8) ] def __init__(self, uuidstr): uuid = UUID(uuidstr) ctypes.Structure.__init__(self) self.Data1, self.Data2, self.Data3, self.Data4[0], self.Data4[1], rest = uuid.fields for i in range(2, 8): self.Data4[i] = rest>>(8-i-1)*8 & 0xff SHGetKnownFolderPath = windll.shell32.SHGetKnownFolderPath SHGetKnownFolderPath.argtypes = [ ctypes.POINTER(GUID), wintypes.DWORD, wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p) ] def _get_known_folder_path(uuidstr): pathptr = ctypes.c_wchar_p() guid = GUID(uuidstr) if SHGetKnownFolderPath(ctypes.byref(guid), 0, 0, ctypes.byref(pathptr)): raise ctypes.WinError() return pathptr.value FOLDERID_Download = '{374DE290-123F-4565-9164-39C4925E467B}' def get_download_folder(): return _get_known_folder_path(FOLDERID_Download)else: def get_download_folder(): home = os.path.expanduser("~") return os.path.join(home, "Downloads")github上提供了一个更完整的模块,用于从Python检索已知文件夹。



