在代码运行之间保留变量的数据
对于一个学校项目,我正在用Python制作子手游戏。现在,我的代码从字典中选择一个单词,如下所示:
WordList = ["cat", "hat", "jump", "house", "orange", "brick", "horse", "word"]
word = WordList[random.randint(0, len(WordList) - 1)]
现在,必须在运行之前在代码中设置单词列表,但是我添加了在运行时将单词添加到列表中的功能:
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,如果有区别的话。对于任何非最佳代码,我深表歉意。
-
只需对要保留的数据进行腌制。由于用例不需要非常复杂的数据存储,因此酸洗是一个很好的选择。一个小例子:
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)
稍后当您需要再次使用它时,只需加载它:
# load your data back to memory when you need it with open(filename, 'rb') as fi: word_list = pickle.load(fi)
-
您现在具有数据持久性。在这里阅读更多。一些重要的指示:- 请注意
'b'
何时使用open()
打开文件。泡菜通常以二进制格式存储,因此您必须以二进制模式打开文件。 - 我使用了
with
上下文管理器。这样可以确保在我完成对文件的所有工作后,安全关闭该文件。
- 请注意