在代码运行之间保留变量的数据 [英] Keeping the data of a variable between runs of code

查看:86
本文介绍了在代码运行之间保留变量的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个学校项目,我正在用Python制作子手游戏.现在,我的代码从字典中选择了一个单词,如下所示:

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", "house", "orange", "brick", "horse", "word"]
word = WordList[random.randint(0, len(WordList) - 1)]

现在必须在运行之前在代码中设置单词列表,但是我添加了在运行时将单词添加到列表中的功能:

right now the list of words has to be set within the code before running it, but I added the ability to add words to the list while running it:

if command == "add":
    while True:
        print("type a word to add to the dictionary")
        print("type /b to go back to game")
        add = raw_input("word: ")

        if add != "/b":
            WordList = WordList + [add]

            print add, "added!"
        else:
            print("returning to game")
            break

但是,一旦我退出代码,添加的单词显然就不会保存,因此我要么必须手动将所有单词添加到列表中,要么在每次代码启动后将一堆单词添加到列表中.所以我想知道是否有一种简单的方法可以在代码完成后保存变量,以便WordList在下次代码启动时保留添加的单词.我用来编写python的程序是Jetbrains PyCharm,如果有区别的话.对于任何非最佳代码,我深表歉意.

however, once I exit the code, the added words are obviously not saved, so I would either have to manually add all the words to the list, or add a bunch of words to the list once the code starts every time. so I am wondering if there is a simple way that I can have the variable save after the code is finished, so that WordList will keep the added words next time the code starts. the program I use to write python is Jetbrains PyCharm, if that makes a difference. Apologies for any un-optimal code, I'm new to code.

推荐答案

只需对要保留的数据进行腌制.由于您的用例不需要非常复杂的数据存储,因此 pickling 是很好的选择.一个小例子:

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!您现在具有数据持久性.在此处了解更多信息.一些重要的提示:

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

  1. 当我使用open()打开文件时,请注意'b'.泡菜通常以二进制格式存储,因此您必须以二进制模式打开文件.
  2. 我使用了with上下文管理器.这样可以确保在我完成对文件的所有工作后,安全关闭该文件.
  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.

这篇关于在代码运行之间保留变量的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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