【问题标题】:Python Pickling ProblemsPython酸洗问题
【发布时间】:2012-12-16 17:12:12
【问题描述】:

我这里有一些使用“pickle”模块的 python 3 代码。它应该存储游戏的高分。当我再次打开程序时,它反而给了我默认的“A:100...”高分。

def __init__(self):
    self.filename = "highscores.dat"
    self.numScores = 5

    if not os.path.isfile(self.filename):
        self.file = open(self.filename, "wb")
        self.scores = [100 for i in range(self.numScores)]
        self.names = ["A", "B", "C", "D", "E"]
        self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
        self.updateFile()
    else:
        file = open(self.filename, "rb")
        self.highscores = pickle.load(file)
        file.close()
        self.file = open(self.filename, "wb")

        self.names = [highscore[0] for highscore in self.highscores]
        self.scores = [highscore[1] for highscore in self.highscores]

 def addScore(self, name, score):
    self.scores.append(score) #Add new score 
    self.scores.sort(reverse = True) #Sort
    self.names.insert(self.scores.index(score), name)
    self.names = self.names[:self.numScores] # Top 5
    self.scores = self.scores[:self.numScores]
    self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
    self.updateFile()

def updateFile(self):
    pickle.dump(self.highscores, self.file)

这只是我认为问题所在的代码部分。如果需要,我会发布更多。我很乐意回答您的问题。谢谢。

【问题讨论】:

  • 如果您要使用完整的绝对路径名,它会起作用吗?
  • 如“C:\Users\Bobby\Dropbox\LD25\highscores.dat”?我刚刚测试过,也有同样的问题。
  • 您可能希望在__init__ 中插入一条打印语句,以查看那里的.isfile() 测试发生了什么。文件是否已创建?
  • 已经想到了。据我所知,它按预期工作。
  • 接下来的测试是给updateFile()添加打印语句,打印self.highscores

标签: python python-3.x pygame pickle


【解决方案1】:

您每次都需要重新打开文件进行写入。目前,每次分数更改时,您都会在文件中逐个写入新记录。您的文件现在包含几个泡菜,但只读取第一个。

将您的代码更改为:

def __init__(self):
    self.filename = "highscores.dat"
    self.numScores = 5

    if not os.path.isfile(self.filename):
        self.scores = [100 for i in range(self.numScores)]
        self.names = ["A", "B", "C", "D", "E"]
        self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
    else:
        with open(self.filename, "rb") as f:
            self.highscores = pickle.load(f)
        self.names = [highscore[0] for highscore in self.highscores]
        self.scores = [highscore[1] for highscore in self.highscores]

def updateFile(self):
    with open(self.filename, 'wb') as f:
        pickle.dump(self.highscores, f)

addScore 不变。

现在每次分数更改时,从头开始写入高分文件。

【讨论】:

  • 我可以问一些完全不同的问题吗?你有多少年的python经验?
  • 我不得不承认我有点嫉妒:P
  • 实际上阅读您的职业档案让我更加嫉妒:P 我要感谢您在这里与我们分享您的知识!对于像我这样最近开悟的人来说,这意义重大!
  • 谢谢。由于我参加了禁止此类事情的比赛,我无法直接复制此代码,但我能够根据您的解释编写自己的解决方案。
猜你喜欢
  • 1970-01-01
  • 2015-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 2011-04-01
  • 1970-01-01
相关资源
最近更新 更多