python - 查找用户的“Downloads”文件夹

时间:2016-03-07 18:34:11

标签: python directory special-folders

我已经发现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

5 个答案:

答案 0 :(得分:7)

这个相当简单的解决方案(从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')
  • 可以从Microsoft的KNOWNFOLDERID docs
  • 获取GUID
  • 这可以扩展为更通用的其他目录

答案 1 :(得分:6)

正确定位Windows文件夹在Python中有点苦差事。根据涵盖Microsoft开发技术的答案,例如this one,应该使用Vista Known Folder API获取它们。这个API不是由Python标准库包装的(虽然有an issue from 2008请求它),但是无论如何都可以使用ctypes模块来访问它。

调整上述答案以使用下载shown here的文件夹ID并将其与现有的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

答案 2 :(得分:3)

from pathlib import Path
downloads_path = str(Path.home() / "Downloads")

答案 3 :(得分:1)

对于python3 + mac或linux

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

答案 4 :(得分:0)

import os

download_path='/'.join( os.getcwd().split('/')[:3] ) + '/Downloads'