Python: Getting AppData folder in a cross-platform way

老子叫甜甜 提交于 2021-01-20 23:50:33

问题


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.


回答1:


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.)




回答2:


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




回答3:


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')




回答4:


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)



来源:https://stackoverflow.com/questions/19078969/python-getting-appdata-folder-in-a-cross-platform-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!