繁体   English   中英

尝试加载和编辑腌制的字典,出现EOFError

[英]Trying to load and edit a pickled dictionary, getting an EOFError

我正在尝试修改作为教程一部分的书籍中的琐事程序; 我需要使用腌制的字典保存球员的姓名和分数。 我已经使用单独的程序创建了dat文件,以避免读取不存在的文件。

这是琐事程序的代码。

#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 triva 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)

    value = next_line(the_file)

    return category, question, answers, correct, explanation, value

def welcome(title):
    """Welcome the player and get his or her name."""
    print("\t\tWelcome to Trivia Challenge!\n")
    print("\t\t", title, "\n")

def saving(player_name):
    import pickle
    f = open("trivia_scores.dat", "rb+")
    highscores = pickle.load(f)
    if player_name in highscores and score > highscores[player_name]:
        highscores[player_name] = score
        pickle.dump(highscores, f)
    elif player_name not in highscores:
        highscores[player_name] = score
        pickle.dump(highscores, f)

    print("The current high scores are as follows:")
    print(highscores)
    f.close()

def main():
    trivia_file = open_file("trivia.txt", "r")
    title = next_line(trivia_file)
    welcome(title)
    score = 0

#Get the first block
    category, question, answers, correct, explanation, value = 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 is your answer?: ")

        #Check answer
        if answer == correct:
            print("\nRight!", end=" ")
            score += int(value)
        else:
            print("\nWrong!", end=" ")
        print(explanation)
        print("Score:", score, "\n\n")

        #Get the next block
        category, question, answers, correct, explanation, value = next_block(trivia_file)

    trivia_file.close()

    print("That was the last question!")
    print("Your final score is", score)
    return score

player_name = input("First, enter your name: ")
main()
saving(player_name)
input("\n\nPress the enter key to exit.")

此时出现同义错误:

def saving(player_name):
    import pickle
    f = open("trivia_scores.dat", "rb+")
    highscores = pickle.load(f)

问题结束后,程序将尝试运行“保存”模块,(从理论上来说)该模块将打开trivia_scores.dat文件,加载highscores词典,检查玩家的姓名是否在词典中以及其当前分数高于文件中的那个,它将覆盖它。

但是由于某种原因,当程序尝试加载highscores字典时,却收到了此错误消息。

EOFError: Ran out of input

我从未见过此错误。 从一些粗略的谷歌搜索中,我得到的印象是它与试图从一个空文件中读取的程序有关。 但这对我没有意义,因为我专门使用其他程序创建了一个dat文件来防止这种情况的发生:trivia_scores.dat不是空文件。 我什至使用Python Shell进行阅读以确保。

此错误是什么意思,为什么Python不会加载dat文件?

上下文:我正在阅读的书是Michael Dawson撰写的《 Python for Absolute Beginner》。 该程序和我要完成的挑战来自第7章。在添加保存模块之前,该程序运行良好。

您编写的原始trivia_scores.dat文件可能已损坏(也许您未在其上调用close() ?)。 您应该尝试创建一个新文件,并向该文件添加一个预填充的字典。 然后尝试从这个新文件中读取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM