【问题标题】:Trying to load and edit a pickled dictionary, getting an EOFError尝试加载和编辑腌制字典,得到 EOFError
【发布时间】:2017-06-20 16:42:16
【问题描述】:

我正在尝试修改作为教程的一部分的书中的琐事程序;我需要使用腌制字典保存玩家的姓名和分数。我已经使用单独的程序创建了 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 文件,加载高分字典,检查玩家的名字是否在字典中,如果他们当前的分数高于文件中的分数,它会覆盖它。

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

EOFError: Ran out of input

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

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

背景:我正在阅读的书是 Michael Dawson 的 Python for the Absolute Beginner。这个程序和我试图完成的挑战来自第 7 章。在我添加保存模块之前,程序运行良好。

【问题讨论】:

  • 可能在某个时候使用空文件

标签: python dictionary pickle eoferror


【解决方案1】:

可能您编写的原始@​​987654321@ 文件已损坏(也许您没有调用close()?)。您应该尝试创建一个新文件并将预填充的字典添加到该文件中。然后尝试从这个新文件中读取。

【讨论】:

  • 这解决了我最初的问题,但在修复错误后,我正在处理一个不同的问题。还是谢谢。
  • @TimtheEnchanter 以前没有发生过错误吗?可能它被“隐藏”了,因为 EOFError 在它之前发生过。
  • 不,错误是我发布此内容的原因。通过制作一个新的 dat 文件,我得到了停止显示的错误,但现在我正在处理程序逻辑问题。我需要程序打开并附加一个 dat 文件,但如果我使用“ab+”函数,它会再次出现错误,并且我不能使用“wb+”函数,因为它会覆盖其他分数(但不是出于某种原因,我使用其他程序设置的初始值)。
  • @TimtheEnchanter 也许你应该问一个单独的问题,添加更多细节。
  • 我可能会。想先弄明白一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 2018-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
相关资源
最近更新 更多