我目前正在通过python为绝对初学者第三次添加。我正在与本书第七章中的第二个挑战作斗争,因为我不断地遇到一个我不理解的错误。在
挑战在于:
“改进triva挑战游戏,使其在一个文件中保持一个高分数列表。程序应该记录球员的名字和得分,如果球员进入名单。用腌制物品储存高分。”
原始代码
# Trivia Challenge
# Trivia game that reads a plain text file
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]
explanation = next_line(the_file)
return category, question, answers, correct, 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")
title = next_line(trivia_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, 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 += 1
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, explanation = next_block(trivia_file)
trivia_file.close()
print("That was the last question!")
print("You're final score is", score)
main()
input("\n\nPress the enter key to exit.")
我尝试挑战代码
^{pr2}$和令人困惑的错误
Traceback (most recent call last):
File "C:\Users\Cheyne\Desktop\Python\chapter07\Challenges\temp.py", line 104, in <module>
main()
File "C:\Users\Cheyne\Desktop\Python\chapter07\Challenges\temp.py", line 100, in main
high_scores()
File "C:\Users\Cheyne\Desktop\Python\chapter07\Challenges\temp.py", line 54, in high_scores
high_scores = pickle.load(f)
File "C:\Python31\lib\pickle.py", line 1365, in load
encoding=encoding, errors=errors).load()
EOFError
谁能帮我解释一下这里出了什么问题吗?我已经盯着它好几天了。在
在第54行有一个“eoferor”,即“文件结束错误”。在
这就是您试图加载pickle文件的地方,因此,考虑到您没有检查该文件是否实际存在,我猜您没有文件并得到错误。在
您可以自己创建一个初始文件,或者在尝试加载之前检查它是否存在并且有效。在
编辑:我刚刚注意到您以“wb+”的形式打开pickle文件,这意味着您打开它进行写入并尝试读取它。您正在重写文件,它将变为零字节。如果要附加到现有文件,应该使用“a”而不是“w”。同样,在加载之前,请确保文件包含有效数据。在
相关问题 更多 >
编程相关推荐