简体   繁体   中英

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

I'm trying to modify a trivia program found in a book as part of a tutorial; I need to save the name and score of the player using a pickled dictionary. I've already created the dat file using a separate program, to avoid reading from a file that doesn't exist.

This is the code for the trivia program.

#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.")

The eponymous error occurs at this point:

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

When the questions end, the program attempts to run the "saving" module, which (In theory) opens the trivia_scores.dat file, loads the highscores dictionary, checks to see if the player's name is in the dictionary, and if their current score is higher than the one in the file, it overwrites it.

But for some reason, when the program attempts to load the highscores dictionary, instead I get this error message.

EOFError: Ran out of input

I have never seen this error before. From some cursory googling, I got the impression that it has something to do with the program trying to read from an empty file. But that made no sense to me, since I specifically created a dat file using a different program to prevent that from happening: trivia_scores.dat is NOT an empty file. I even read from it with Python Shell to make sure.

What does this error mean, and why won't Python load the dat file?

Context: The book I'm reading from is Python for the Absolute Beginner, by Michael Dawson. This program and the challenge I'm trying to complete come from chapter 7. The program was running fine before I added the saving module.

Probably the original trivia_scores.dat file you wrote got corrupt (maybe you didn't call close() on it?). You should try creating a new file and adding a pre-populated dictionary to this file. Then try reading from this new file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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