2015-04-16 4 views
0

Как вы можете сохранить и загрузить переменную, используя pickle? Я пытаюсь сохранить и загрузить высокий балл от мелочей. Вот соответствующий код:Pickle in Python

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

Проблема возникает каждый раз, когда оценка и высокий уровень равны. high = 0 каждый раз, потому что каждый раз, когда я получаю ошибку конца файла. Поэтому, когда я запускаю окончательный оператор печати, он всегда печатает текущий счет.

Heres весь код, если вы хотите:

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

две вещи: 1. '«»WB +' режим обрезает файл, так что вы потеряете все предыдущие данные (http://stackoverflow.com/q/16208206/3001761). 2. Если вы используете правильный режим, вам нужно подумать о том, где будет отображаться «указатель» файла после каждой операции. – jonrsharpe

+0

Какой режим файла вы бы рекомендовали для сохранения и загрузки? @jonrsharpe – JGerulskis

+0

Честно говоря, было бы проще, если бы вы открыли файл один раз для чтения, снова закрыли его, а затем открыли отдельно для записи. Вы также должны использовать менеджер контекста 'with':' open (filename, mode) как file_: ... ' – jonrsharpe

ответ

4

Если открыть с режимом 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