Python:以跨平台的方式获取AppData文件夹

use*_*098 12 python appdata

我想要一个代码片段,在所有平台(至少是Win/Mac/Linux)上获取适当的app数据目录(配置文件等).例如:Windows上的%APPDATA%/.

Jas*_*n S 11

如果您不介意使用appdirs模块,它应该可以解决您的问题.(cost =您需要安装模块或将其直接包含在Python应用程序中.)

  • 观点已采纳,但 FWIW SO 特别提到“所有贡献均已获得知识共享许可,并且该网站是协作编辑的,就像维基百科一样。” 在编辑帖子指南中 - https://stackoverflow.com/help/editing。 (3认同)
  • 为什么要恢复编辑,添加自述文件中的使用示例以使这个答案完整?!如您所知,好的答案是完整的,而不是仅仅“单击此链接”。删除高度相关且有价值的使用信息感觉有点被动攻击......根据 https://stackoverflow.com/help/how-to-answer:“鼓励链接到外部资源,但请在链接周围添加上下文,以便您的同事用户将知道它是什么以及为什么它在那里。**始终引用重要链接的最相关部分,以防外部资源无法访问或永久离线。**” (2认同)

Hon*_*Abe 9

Qt 的QStandardPaths 文档列出了这样的路径。

使用 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
Run Code Online (Sandbox Code Playgroud)

Python文档建议sys.platform.startswith('linux')与旧版本的Python传回了像“linux2上”或“linux3”兼容性“成语”。


小智 1

我建议研究“appdata”在您想要使用该程序的操作系统中的位置。一旦您知道了位置,您就可以简单地使用 if 语句来检测操作系统和 do_something()。

import sys
if sys.platform == "platform_value":
    do_something()
elif sys.platform == "platform_value":
    do_something()
Run Code Online (Sandbox Code Playgroud)
  • 系统:平台值
  • Linux(2.x 和 3.x):“linux2”
  • Windows:“win32”
  • Windows/Cygwin:“cygwin”
  • Mac OS X:“达尔文”
  • 操作系统/2:'os2'
  • OS/2 EMX:“os2emx”
  • RiscoOS:“riscos”
  • AtheOS:'atheos'

列表来自官方 Python 文档。(搜索“sys.platform”)

  • Python 致力于将事物抽象为公共库;为什么没有一个通用的函数来做到这一点? (4认同)