Python: Getting AppData folder in a cross-platform way

前端 未结 4 1633
终归单人心
终归单人心 2021-02-12 21:03

I\'d like a code snippet that gets the proper directory for app data (config files, etc) on all platforms (Win/Mac/Linux at least). For example: %APPDATA%/ on Windows.

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-12 21:54

    You can use the following function to get user data dir, tested in linux and w10 (returning AppData/Local dir) it's adapted from the appdirs package:

    import sys
    from pathlib import Path
    from os import getenv
    
    def get_user_data_dir(appname):
        if sys.platform == "win32":
            import winreg
            key = winreg.OpenKey(
                winreg.HKEY_CURRENT_USER,
                r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
            )
            dir_,_ = winreg.QueryValueEx(key, "Local AppData")
            ans = Path(dir_).resolve(strict=False)
        elif sys.platform == 'darwin':
            ans = Path('~/Library/Application Support/').expanduser()
        else:
            ans=Path(getenv('XDG_DATA_HOME', "~/.local/share")).expanduser()
        return ans.joinpath(appname)
    
    

提交回复
热议问题