python - 我的代码不断删除用户分数和姓名
问题描述
我是编程的新手,我尝试编写一个简单的代码,该代码应该向用户提出问题并在答案正确时添加一个点,如果答案错误则删除该点。当我尝试为他们下次打开“游戏”时保存分数时出现问题。
我的代码如下所示:
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混合with open ...
- 您应该尝试坚持一种风格(并且with ...
是推荐的方式)。
通常,不要尝试使用多个句柄同时访问同一个文件,除非您知道这是您想要的。
推荐阅读
- java - 如果我在 64 位系统中安装 32 位 Android Studio,它会正常工作吗?
- c# - C#使用powershell使用tails
- swift - 如何使用 vapor 3.x 构建蒸汽工具箱
- hadoop - 如果列中的值发生更改,则查询以捕获行
- c++ - 从向量中删除对象指针
- r - selectInput 基于上传 csv 文件的列
- tensorflow - CNN 模型在 CPU 和 GPU 上 tensorflow 预测的差异
- templates - SystemVerilog 中的参数化端口声明
- javascript - Firebase + React - 不改变我的状态
- rest - delphi rest getdatasnapWebModule