我有一个包含名字和结果的文本文件。如果名称已存在,则只应更新结果。我尝试了这个代码和其他许多代码,但没有成功。你知道吗
文本文件的内容如下所示:
Ann, 200
Buddy, 10
Mark, 180
Luis, 100
附言:我两周前就开始了,所以不要评判我的错误代码。你知道吗
from os import rename
def updatescore(username, score):
file = open("mynewscores.txt", "r")
new_file = open("mynewscores2.txt", "w")
for line in file:
if username in line:
splitted = line.split(",")
splitted[1] = score
joined = "".join(splitted)
new_file.write(joined)
new_file.write(line)
file.close()
new_file.close()
maks = updatescore("Buddy", "200")
print(maks)
所以最需要区别的是,在for循环中,你说要在新的文本文件中放一行,但从来没有说过要在想要替换分数时不这样做,所需要的只是if语句下面的else语句:
我建议将csv作为字典读入,只更新一个值。你知道吗
你可以试试这个,如果用户名不存在就添加,否则就更新它。你知道吗
相关问题 更多 >
编程相关推荐