如何在 Python 中存储变量/首选项以备后用 [英] How to store variables/preferences in Python for later use

查看:46
本文介绍了如何在 Python 中存储变量/首选项以备后用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用适用于 Windows 的 Python 开发一个程序,我想保存变量和用户首选项,以便即使在程序终止并重新启动后我也可以调用它们.

I'm working on a program in Python for Windows, and would like to save variables and user preferences so that I can recall them even after the program has been terminated and restarted.

在 Windows 机器上有没有一种理想的方法可以做到这一点?_winreg 和 Windows 注册表是否适合此任务?还是我需要创建某种自己的数据库?

Is there an ideal way to do this on Windows machines? Would _winreg and the Windows registry be suited for this task? Or do I need to create some sort of database of my own?

推荐答案

您通常希望将其存储在home"文件夹中的配置文件夹中.这在 *nix 系统上很容易,在 windows 中更难,因为您实际上需要获取应用程序数据"目录.这通常对我有用:

You're usually going to want to store it in a configuration folder in the "home" folder. That's easy on *nix systems, more difficult in windows, because you actually need to get the "application data" directory. This usually works for me:

import os
if os.name != "posix":
    from win32com.shell import shellcon, shell
    homedir = "{}\\".format(shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0))
else:
    homedir = "{}/".format(os.path.expanduser("~"))

有了主目录后,您应该创建一个以您的项目命名的文件夹:

After you have the homedirectory, you should create a folder named after your project:

if not os.path.isdir("{0}.{1}".format(homedir,projectname)):
    os.mkdir("{0}.{1}".format(homedir,projectname))

然后您可以在该文件夹中创建一个配置文件,并以您选择的格式将您的选项写入其中(我个人最喜欢的是 XML).

Then you can make a config file in that folder and write your options to it in the format of your choosing (my personal favorite is in an XML).

这篇关于如何在 Python 中存储变量/首选项以备后用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆