Python 我的代码不断删除用户分数和名称
我是一个编程新手,我试着写一个简单的代码,它应该是问用户一个问题,如果答案是正确的,就加一分,如果答案是错误的,就去掉一分。当我试图保存分数以便下次他们打开“游戏”时,问题就出现了 我的代码如下所示:Python 我的代码不断删除用户分数和名称,python,python-3.x,Python,Python 3.x,我是一个编程新手,我试着写一个简单的代码,它应该是问用户一个问题,如果答案是正确的,就加一分,如果答案是错误的,就去掉一分。当我试图保存分数以便下次他们打开“游戏”时,问题就出现了 我的代码如下所示: from random import randint as ran from os import remove as rem from os import rename as ren name = input("Whats ur name?(th
from random import randint as ran
from os import remove as rem
from os import rename as ren
name = input("Whats ur name?(the name is case sensitive)\n")
sco = []
i = -1
s = 0
NewUser = False
update = open ("score.tmp", "w")
getpoint = open ("score.txt", "r")
for line in getpoint:
a = line.split()
sco.append(a)
getpoint.close()
try:
for item in sco:
i = i + 1
if(sco[i][0]) == name:
s = sco[i][1]
break
else:
continue
except:
NewUser = True
#some random code here
if NewUser == True:
with open ("score.txt", "a") as the:
the.write(name + " " + str(s) + "\n")
elif NewUser == False:
sco[i][1] = s
Update = (str(sco).strip("[]"))
update.write(Update)
rem("score.txt")
update.close()
ren("score.tmp", "score.txt")
现在,在这两种情况下(NewUser==True和NewUser==False),score.txt文件中以前的分数都会被删除。甚至在几天前,由于某种原因,同一代码“正常工作”,例如,如果score.txt如下所示:
Ann 100
Daven 180
Bella 90
Brandon 80
代码将返回以下内容:
[Ann], [100], [Daven], [180], [Bella], [90], [Brandon], [80]
这使得下次有人运行程序时,程序无法正常运行:(
请帮助解决此问题。这是因为这一行:
update = open ("score.tmp", "w")
这会打开文件进行写入,如果存在,则会将其截断。这是您第一次访问该文件,因此它被删除。它刚刚被归零
作为一种修复方法,这一行应该移动到使用它的write()
之前。另外,您将open()/close()
与pythonic和open…
混合在一起-您应该尝试坚持一种风格(建议使用和…
)
通常,不要尝试使用多个句柄同时访问同一文件,除非您知道这是您想要的