Pickle用户名/得分EOF错误Python

时间:2013-11-06 10:00:25

标签: python pickle

我很新,我为可能用一个我想念的简单答案提出问题而道歉,但我花了3个小时试图让这段代码与更大的程序一起工作,我就是用尽头发拉出来。我一直在收到EOFError

score = 12

def scor_func(score):
  scores = []
  name = input("Please enter your name: ")
  entry = (name, score)
  scores.append(entry)
  f = open("Triviascores.bat", "wb+")
  pickle.dump(scores, f)

  scores = pickle.load(f)
  f.close()
  return scores

scor_func(score)

2 个答案:

答案 0 :(得分:2)

dump之后关闭文件,然后在load

之前再次打开它
import pickle

score = 12

def scor_func(score):
  scores = []
  name = input("Please enter your name: ")
  entry = (name, score)
  scores.append(entry)
  f = open("Triviascores.bat", "wb")
  pickle.dump(scores, f)

  f.close()

  f = open("Triviascores.bat", "rb")
  scores = pickle.load(f)
  f.close()
  return scores

scor_func(score)

如果你需要存储然后立即检索一个对象,你最好使用shelve,这是标准库的一部分。

答案 1 :(得分:1)

您必须close文件才能刷新和关闭数据流。

  f = open("Triviascores.bat", "wb+")
  pickle.dump(scores, f)
  f.close()

  f = open("Triviascores.bat", "r")
  scores = pickle.load(f)
  f.close()