[英]Pickle in Python
如何使用pickle保存和加载变量 ? 我正在尝试从琐事游戏中保存并加载高分。 以下是相关代码:
high_scorz=open_file("high.dat", "wb+")
high = 0
try:
high=pickle.load(high_scorz)
except EOFError:
print("EOF ERROR!!!!")
finally:
print("NO DATA RECEIVED")
# later in the code when score has been updated
if score > high:
pickle.dump(score, high_scorz)
high = score
trivia_file.close()
high_scorz.close()
print("High Scorz: " + str(high))
问题是每次得分和高分相等。 每次high = 0
因为每次我收到文件结尾错误。 因此,当我运行最终打印语句时,它将始终打印当前分数。
如果需要,这里是所有代码:
# Trivia Challenge
# Trivia game that reads a plain text file
import pickle
import sys
def open_file(file_name, mode):
"""Open a file."""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program.\n", e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
"""Return the next block of data from the trivia file."""
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
points = next_line(the_file)
explanation = next_line(the_file)
return category, question, answers, correct, points, explanation
def welcome(title):
"""Welcome the player and get his/her name."""
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")
def main():
trivia_file = open_file("trivia.txt", "r")
high_scorz=open_file("high.dat", "wb+")
high = 0
try:
high=pickle.load(high_scorz)
except EOFError:
print("EOF ERROR!!!!")
finally:
print("NO DATA RECEIVED")
title = next_line(trivia_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, points, explanation = next_block(trivia_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer
answer = input("What's your answer?: ")
# check answer
if answer == correct:
print("\nRight!", end=" ")
score += int(points)
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, points, explanation = next_block(trivia_file)
print("That was the last question!")
print("You're final score is", score)
if score > high:
pickle.dump(score, high_scorz)
high = score
trivia_file.close()
high_scorz.close()
print("High Scorz: " + str(high))
main()
input("\n\nPress the enter key to exit.")
如果您有打开w
模式,你在w ^仪式任何以前的数据。 两次打开文件会更容易:
filename = "high.dat"
with open(filename) as high_scores:
try:
high_score = pickle.load(high_scores)
except Exception:
print("No data loaded")
high_score = 0
# later in the code when score has been updated
if score > high_score:
with open(filename, 'w') as high_scores:
pickle.dump(score, high_scores)
high_score = score
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.