Search code examples
pythonlistbotsirctwitch

Python - Store variables in a list that save each time program restarts


I am stuck on a seemingly simple task with a Python Twitch IRC Bot I'm developing for my channel. I have a points system all figured out, and I thought it was working, but I found out that every time I restart the program, the list that contains balances of users resets.

This is because I declare the empty list at the beginning of the script each time the program is run. If a user chats and they aren't in the list of welcomed users, then the bot will welcome them and add their name to a list, and their balance to a corresponding list.

Is there someway I can work around this resetting problem and make it so that it won't reset the list every time the program restarts? Thanks in advance, and here's my code:

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

(I had attempted to use global variables to overcome this problem, however they didn't work, although I'm guessing I didn't use them right :P)


Solution

  • Try using the json module to dump and load your list. You can catch file open problems when loading the list, and use that to initialize an empty list.

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