我正在玩pygame游戏并希望保存高分。每次我退出并重新运行我的代码时,分数都不会保存到我的文件中。我已经研究过可能存在的问题并试图手动关闭而不是。如果有人知道我可能从下面的代码中做了什么,我将非常感激。(请记住,我已经在代码的其他地方定义了分数)
#This opens the file and sets the score as self.highscore
HS_FILE = "highscore.txt"
self.dir = path.dirname(__file__)
with open(path.join(self.dir, HS_FILE), 'w') as f:
try:
self.highscore = int(f.read())
except:
self.highscore = 0
#This is elsewhere in the code but the code around it runs fine
#self.score is created elsewhere
if self.score > self.highscore:
self.highscore = self.score
with open(path.join(self.dir, HS_FILE), 'w') as f:
f.write(str(self.score))
#for the purpose of confusion I will just print out the score to the command line
print(str(self.highscore))
答案 0 :(得分:2)
with open(path.join(self.dir, HS_FILE), 'w') as f:
您正在以写入模式('w')打开文件,然后尝试从中读取哪些文件无效。因为您使用了捕获所有内容的except子句,所以您没有看到如下所示的错误:
io.UnsupportedOperation: not readable
此外,因为你正在使用with语句,所以文件在写入模式下打开然后再次关闭,正如评论者已经指出的那样,实际上会导致文件被清空。使用读取模式('r')打开文件,看看是否能解决问题。