python - 查找用户的 "Downloads" 文件夹

python - Finding the user's "Downloads" folder

我已经找到 this question 建议使用 os.path.expanduser(path) 来获取用户的主目录。

我想用 "Downloads" 文件夹实现同样的效果。我知道 this is possible in C#,但我是 Python 的新手,不知道这在这里是否也可行,最好与平台无关(Windows、Ubuntu)。

我知道我可以做到 download_folder = os.path.expanduser("~")+"/Downloads/",但 (at least in Windows) it is possible to change the Default download folder

正确定位 Windows 个文件夹在 Python 中有点麻烦。根据涵盖 Microsoft 开发技术的答案,例如 this one, they should be obtained using the Vista Known Folder API. This API is not wrapped by the Python standard library (though there is an issue from 2008 请求它),但无论如何都可以使用 ctypes 模块访问它。

调整上述答案以使用文件夹 ID 进行下载 shown here 并将其与您现有的 Unix 代码结合起来应该会产生如下所示的代码:

import os

if os.name == 'nt':
    import ctypes
    from ctypes import windll, wintypes
    from uuid import UUID

    # ctypes GUID copied from MSDN sample code
    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")

从 Python 检索已知文件夹的更完整模块是 available on github

这个相当简单的解决方案(扩展自 this reddit post)对我有用

import os

def get_download_path():
    """Returns the default downloads path for linux or windows"""
    if os.name == 'nt':
        import winreg
        sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
        downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}'
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:
            location = winreg.QueryValueEx(key, downloads_guid)[0]
        return location
    else:
        return os.path.join(os.path.expanduser('~'), 'downloads')
  • GUID可以从微软的KNOWNFOLDERID docs
  • 获取
  • 这可以扩展到更通用的其他目录

对于python3+mac或linux

from pathlib import Path
path_to_download_folder = str(os.path.join(Path.home(), "Downloads"))
from pathlib import Path
downloads_path = str(Path.home() / "Downloads")