python - Finding the user's “Downloads” folder

后端 未结 4 1885
逝去的感伤
逝去的感伤 2020-12-05 14:53

I already found this question that suggests to use os.path.expanduser(path) to get the user\'s home directory.

I would like to achieve the same with the

4条回答
  •  一整个雨季
    2020-12-05 15:29

    This fairly simple solution (expanded from this reddit post) worked for me

    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')
    
    • The GUID can be obtained from Microsoft's KNOWNFOLDERID docs
    • This can be expanded to work more generically other directories

提交回复
热议问题