0
我想創建一個非常基本的記分板系統。要從文件讀入列表中的分數。如果名稱存在,則將使用更多分數更新列表(追加)。如果名稱不存在,則創建新行。我認爲它的附加新分數列表不起作用。任何幫助表示讚賞 - 學習。更新基於搜索追加的Python列表
message=""
#ask for name and score
name = input("Please enter the name you wish to add")
score = input("Please enter the high score")
#open the highscores line and read in all the lines to a list called ScoresList.
# Then close the file.
scoresFile = open("highscores.txt","r")
ScoresList = scoresFile.readlines()
scoresFile.close()
#for each line in the ScoresList list
for i in range(0, len(ScoresList)):
#check to see if the name is in the line
if name in ScoresList[i]:
#append new score to list
tempscore= ScoresList[i]
ScoresList[i]=tempscore.append(score)
message="Updated"
#write the scores back to the file. Overwrite with the new list
scoresFile = open("highscores.txt","w")
for line in ScoresList:
scoresFile.write(line + "\n")
scoresFile.close()
else:
message = "Not updated"
if message=="":
scoresFile = open("highscores.txt","a")
scoresFile.write(name + str(score)+"\n")
scoresFile.close()
謝謝。只注意到我有循環問題。我添加了一個消息變量來試圖解決這個問題。我知道代碼非常粗糙 - 學習。 – learningpython
您的問題是'ScoresList [i] = tempscore.append(分數)'使得'ScoresList [i] == None' –
謝謝。經過德'重建我現在明白了。我如何獲得旁邊的新分數,而不是換行。只希望每個使用名稱出現一次。 '如果line.split中的名字'做什麼? Arthur,9,12,10等 – learningpython