-1

I am currently working through the python for absolute beginners 3rd addition. I am struggling with the 2nd challenge in the 7th chapter of the book, as i keep getting an error i don't understand.

The challenge is to:

"improve triva challenge game so that it maintains a high score list in a file. The program should records the player's name and score if the player makes the list. store the high scores using a pickled object."

The original code

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

my attempt at the challenge code

# Trivia Challenge
# Trivia game that reads a plain text file

import sys, pickle   

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)

    points = 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, points, 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 high_scores():
    global score
    value = int(score)
    name = input("What is your name? ")
    entry = (value, name)
    f = open("high_scores.dat", "wb+")
    high_scores = pickle.load(f)
    high_scores.append(entry)
    high_scores = high_scores[:5]
    print("High Scores\n")
    print("NAME\tSCORE")
    for entry in high_scores:
        value, name = entry
        print(name, "\t", value)
    pickle.dump(high_scores, f)
    f.close()

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

    # get first block
    category, points, 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=" ")
            j = int(points)
            global score
            score += j
        else:
            print("\nWrong.", end=" ")
        print(explanation)
        print("Score:", score, "\n\n")

        # get next block
        category, points, question, answers, correct, explanation = next_block(trivia_file)

    trivia_file.close()

    print("That was the last question!")
    print("You're final score is", score)
    high_scores()

score = 0

main()  
input("\n\nPress the enter key to exit.")

And the wonderfully confusing error

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

Can anyone help explain what's going wrong here please? I have been staring at it for days.

  • Please share with us how the code is used. What is your main function? – harfel Apr 18 '16 at 11:08
  • 4
    Don't put every version of Python that was ever made into your tags. The tags are meant to categorize your question. What version is it really? Use that tag. Usually, the general `python-3.x` tag is enough. – zondo Apr 18 '16 at 11:11
  • @ChatterOne The pickle file is there i have checked and made a new file and tried that one to the same result. – C. Bransby Apr 18 '16 at 11:50

1 Answers1

0

You have an "EOFError", which is an "End Of File Error" at line 54.

That's where you try to load the pickle file so, considering that you are not checking that the file actually exists, my guess is that you have no file and get the error.

Either create an initial file by yourself, or check that it exists and is valid before trying to load it.

EDIT: I just noticed that you open the pickle file as "wb+", which means that you open it for writing and try to read it. You're overwriting the file, which becomes zero bytes. If you want to append to the existing file, you should use "a" instead of "w". Again, before loading make sure the file contains valid data.

ChatterOne
  • 3,381
  • 1
  • 18
  • 24