[英]Find name in file and then replace their score in python
I have written a game and stored the players scores in a file. 我已经编写了一个游戏,并将玩家分数存储在一个文件中。 However I want to make it so that if a person plays more than once their new scores are stored next to their name, and old scores, in a file.
但是,我想这样做的目的是,如果一个人玩的次数超过一次,则其新乐谱将存储在文件名和旧乐谱旁边。 Here is the code I have written so far.
这是我到目前为止编写的代码。 I appreciate any help!
感谢您的帮助! Thanks!
谢谢!
scores = open('scores.txt', 'r+')
scores.write("Name:%s Score:%d---" % (name,score))
scorel = scores.read()
print (scorel)
scores.close()
PS as you can probably tell I am new to Python! 您可能会告诉我PS是Python的新手!
This is a crude way of accomplishing what you needed. 这是完成所需内容的粗略方法。 Note that this might get slow for very large files.
请注意,这对于大型文件可能会变慢。 You'll need to create a blank .txt file called
oldscores.txt
manually the first time you run this. 首次运行时,您
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.