Python - 将变量存储在每次程序重新启动时保存的列表中
Python - Store variables in a list that save each time program restarts
我正在为我的频道开发一个 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 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...")