[英]Find name in file and then replace their score in python
我已经编写了一个游戏,并将玩家分数存储在一个文件中。 但是,我想这样做的目的是,如果一个人玩的次数超过一次,则其新乐谱将存储在文件名和旧乐谱旁边。 这是我到目前为止编写的代码。 感谢您的帮助! 谢谢!
scores = open('scores.txt', 'r+')
scores.write("Name:%s Score:%d---" % (name,score))
scorel = scores.read()
print (scorel)
scores.close()
您可能会告诉我PS是Python的新手!
这是完成所需内容的粗略方法。 请注意,这对于大型文件可能会变慢。 首次运行时,您oldscores.txt
手动创建一个名为oldscores.txt
的空白.txt文件。
def writeScore(name, score):
name = str(name)
score = str(score)
if name in b:
index = b.index(name)
f.seek(0,0)
with open('oldscores.txt', 'a') as f2:
f2.write(a[index])
if index == (len(b)-1):
newscore = a[index].rstrip("\n").split(" ")
newscore[3] = score
a[index] = " ".join(newscore)
else:
newscore = a[index].rstrip("\n").split(" ")
newscore[3] = score + "\n"
a[index] = " ".join(newscore)
for i in a:
f.write(i)
else:
f.write("\nname: {} score: {}".format(name, score))
with open('scores.txt', 'r+') as f:
a = f.readlines()
b = [i.split(" ")[1] for i in a]
writeScore(PLAYERNAME,SCORE) # Enter the name of the player and the score in here.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.