Python 泡菜

Pickle in Python

如何使用 pickle 保存和加载变量?我正在尝试从问答游戏中保存和加载高分。这是相关代码:

high_scorz=open_file("high.dat", "wb+")
high = 0
try:
    high=pickle.load(high_scorz)
except EOFError:
    print("EOF ERROR!!!!")
finally:
    print("NO DATA RECEIVED")

# later in the code when score has been updated

if score > high:
    pickle.dump(score, high_scorz)
    high = score
trivia_file.close()
high_scorz.close()
print("High Scorz: " + str(high))

问题是每次score和high都相等。 high = 0 每次都是因为每次我都收到文件结尾错误。因此,当我 运行 最后的打印语句时,它总是打印当前分数。

如果需要,这里是所有代码:

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

import pickle

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]

    points = next_line(the_file)

    explanation = next_line(the_file)

    return category, question, answers, correct, points, 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")
    high_scorz=open_file("high.dat", "wb+")
    high = 0
    try:
        high=pickle.load(high_scorz)
    except EOFError:
        print("EOF ERROR!!!!")
    finally:
        print("NO DATA RECEIVED")
    title = next_line(trivia_file)
    welcome(title)
    score = 0

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

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

    print("That was the last question!")
    print("You're final score is", score)
    if score > high:
        pickle.dump(score, high_scorz)
        high = score
    trivia_file.close()
    high_scorz.close()

    print("High Scorz: " + str(high))

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

如果您以 w 模式打开,您会覆盖w写入任何以前的数据。两次打开文件会更容易:

filename = "high.dat"

with open(filename) as high_scores:
    try:
        high_score = pickle.load(high_scores)
    except Exception:
        print("No data loaded")
        high_score = 0

# later in the code when score has been updated

if score > high_score:
    with open(filename, 'w') as high_scores:
        pickle.dump(score, high_scores)
    high_score = score