Keeping the data of a variable between runs of code

前端 未结 3 2165
星月不相逢
星月不相逢 2020-12-05 22:16

For a school project I am making a hangman game in Python. Right now my code picks a word from a dictionary like so:

WordList = [\"cat\", \"hat\", \"jump\",          


        
相关标签:
3条回答
  • 2020-12-05 22:29

    Simply pickle the data you want to keep persistent. Since your use case doesn't require very complex data storage, pickling is a very good option. A small example:

    import pickle
    
    word_list = ["cat", "hat", "jump", "house", "orange", "brick", "horse", "word"]
    
    # do your thing here, like
    word_list.append("monty")
    
    # open a pickle file
    filename = 'mypickle.pk'
    
    with open(filename, 'wb') as fi:
        # dump your data into the file
        pickle.dump(word_list, fi)
    

    Later when you need to use it again, just load it up:

    # load your data back to memory when you need it
    with open(filename, 'rb') as fi:
        word_list = pickle.load(fi)
    

    Ta-da! You have data persistence now. More reading here. A few important pointers:

    1. Notice the 'b' when I use open() to open a file. Pickles are commonly stored in a binary format, so you must open the file in a binary mode.
    2. I used the with context manager. This ensures that a file is safely closed once all my work with the file is done.
    0 讨论(0)
  • 2020-12-05 22:29

    If you exit the code you stop the process. For this reason you lose all data. You have to add the words keeping the script alive. The suggestion is to use a server that processing all your calls (example: http://flask.pocoo.org/) or to use the python command input (https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output).

    But remember... if you stop the process you lose all data, it is normal.

    Otherwise, before stopping your script, you have to save all the data into a file or database and load them when the script starts.

    0 讨论(0)
  • 2020-12-05 22:30

    You have to use persistent storage: write the words in a file when you add them and retrieve them from this file when the program starts.

    0 讨论(0)
提交回复
热议问题