Python-将每次重新启动程序时保存的变量存储在列表中 [英] Python - Store variables in a list that save each time program restarts

查看:31
本文介绍了Python-将每次重新启动程序时保存的变量存储在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的频道开发的Python Twitch IRC Bot执行一项看似简单的任务。我有一个积分系统,我以为它起作用了,但我发现每次我重新启动程序时,包含用户余额的列表都会重置。

这是因为我在每次运行程序时在脚本的开头声明了空列表。如果用户聊天时不在欢迎用户列表中,那么机器人会欢迎他们,并将他们的名字添加到列表中,并将余额添加到相应的列表中。

有没有什么办法可以解决这个重置问题,使它不会在每次程序重新启动时都重置列表?提前谢谢,我的代码是:

welcomed = []
balances = []

def givePoints():
    global balances
    threading.Timer(60.0, givePoints).start()
    i = 0
    for users in balances:
        balances[i] += 1
        i += 1
def welcomeUser(user):
    global welcomed
    global balances
    sendMessage(s, "Welcome, " + user + "!")
    welcomed.extend([user])
    balances.extend([0])

givePoints()
#other code here...

if '' in message:
    if user not in welcomed:
        welcomeUser(user)
break

(我曾尝试使用全局变量来解决此问题,但是它们不起作用,尽管我猜我没有正确使用它们:p)

推荐答案

尝试使用json模块转储和加载您的列表。您可以在加载列表时捕获文件打开问题,并使用该问题来初始化空列表。

import json

def loadlist(path):
    try:
        with open(path, 'r') as listfile:
            saved_list = json.load(listfile)
    except Exception:
            saved_list = []
    return saved_list

def savelist(path, _list):
    try:
        with open(path, 'w') as listfile:
            json.dump(_list, listfile)
    except Exception:
        print("Oh, no! List wasn't saved! It'll be empty tomorrow...")

这篇关于Python-将每次重新启动程序时保存的变量存储在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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