Python: Getting AppData folder in a cross-platform way

前端 未结 4 1634
终归单人心
终归单人心 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:35

    If you don't mind using the appdirs module, it should solve your problem. (cost = you either need to install the module or include it directly in your Python application.)

    0 讨论(0)
  • 2021-02-12 21:40

    Qt's QStandardPaths documentation lists paths like this.

    Using Python 3.8

    import sys
    import pathlib
    
    def get_datadir() -> pathlib.Path:
    
        """
        Returns a parent directory path
        where persistent application data can be stored.
    
        # linux: ~/.local/share
        # macOS: ~/Library/Application Support
        # windows: C:/Users/<USER>/AppData/Roaming
        """
    
        home = pathlib.Path.home()
    
        if sys.platform == "win32":
            return home / "AppData/Roaming"
        elif sys.platform == "linux":
            return home / ".local/share"
        elif sys.platform == "darwin":
            return home / "Library/Application Support"
    
    # create your program's directory
    
    my_datadir = get_datadir() / "program-name"
    
    try:
        my_datadir.mkdir(parents=True)
    except FileExistsError:
        pass
    

    The Python documentation recommends the sys.platform.startswith('linux') "idiom" for compatibility with older versions of Python that returned things like "linux2" or "linux3".

    0 讨论(0)
  • 2021-02-12 21:50

    I recommend researching the locations of 'appdata' in the operating systems that you want to use this program on. Once you know the locations you could simple use if statements to detect the os and do_something().

    import sys
    if sys.platform == "platform_value":
        do_something()
    elif sys.platform == "platform_value":
        do_something()
    
    • System: platform_value
    • Linux (2.x and 3.x): 'linux2'
    • Windows: 'win32'
    • Windows/Cygwin: 'cygwin'
    • Mac OS X: 'darwin'
    • OS/2: 'os2'
    • OS/2 EMX: 'os2emx'
    • RiscOS: 'riscos'
    • AtheOS: 'atheos'

    List is from the official Python docs. (Search for 'sys.platform')

    0 讨论(0)
  • 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)
    
    
    0 讨论(0)
提交回复
热议问题