我写了一个游戏并将玩家分数存储在一个文件中。但是我想这样做,以便如果一个人不止一次地播放他们的新分数存储在他们的名字和旧分数旁边的文件中。这是我到目前为止编写的代码。我感谢任何帮助!谢谢!
scores = open('scores.txt', 'r+')
scores.write("Name:%s Score:%d---" % (name,score))
scorel = scores.read()
print (scorel)
scores.close()
P.S你可能会说我是Python的新手!
答案 0 :(得分:0)
这是完成所需内容的粗略方式。请注意,对于非常大的文件,这可能会变慢。第一次运行时,您需要手动创建名为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.