Python: Getting AppData folder in a cross-platform way

前端 未结 4 1601
南方客
南方客 2021-02-12 20:52

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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-12 21:56

    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)
    
    

提交回复
热议问题