Python: Getting AppData folder in a cross-platform way

前端 未结 4 1598
南方客
南方客 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条回答
  •  不知归路
    2021-02-12 21:47

    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//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".

提交回复
热议问题