[英]My code keeps deleting user scores and names
我是编程的新手,我尝试编写一个简单的代码,该代码应该向用户提出问题并在答案正确时添加一个点,如果答案错误则删除该点。 当我尝试为他们下次打开“游戏”时保存分数时出现问题。
我的代码如下所示:
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]
这使得程序不可能在下次有人运行它时立即执行 function :(
请帮助解决这个问题。
这是因为这条线:
update = open ("score.tmp", "w")
打开文件进行写入,如果存在则截断它。 这是您第一次访问该文件,因此印象它已被删除。 它刚刚归零。
作为修复,应该将此行移到write()
使用它之前。 此外,您正在将open()/close()
与 pythonic with open...
混合使用 - 您应该尝试坚持一种风格(并且with...
是推荐的方式)。
通常,不要尝试使用多个句柄同时访问同一个文件,除非您知道这是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.