我正在为一个可以在文本文件中添加/删除/读取高分和名称的程序编写一个函数。我有addscore函数工作,但似乎无法找出删除选定的名称和文本文件的高分。这就是我如何启动delete函数的,我也有一些其他的代码,但都没有意义。事先谢谢你的帮助。你知道吗
import os
def deleteScore():
nameDelete = input("Enter a name you would like to delete... ")
deleteFile = open("highscores.txt", "r")
deleteList = deleteFile.readlines()
deleteFile.close()
这也是addscore函数,它工作正常,并以以下格式写入文本文件:
jim99
def addScore():
#asks user for a name and a score
name = input("Please enter the name you want to add... ")
score = inputInt("Please enter the highscore... ")
message = ""
#opens the highscore file and reads all lines
#the file is then closed
scoresFile = open("highscores.txt","r")
scoresList = scoresFile.readlines()
scoresFile.close()
#for each line in the list
for i in range(0, len(scoresList)):
#checks to see if the name is in the line
if name in scoresList[i]:
#if it is then takes the name from the text to leave the score
tempscore = scoresList[i].replace(name, "")
#if the score is new then add to the list
if int(tempscore) < score:
message = "Score Updated"
scoresList[i] = (name + str(score))
#Writes the score back into the file
scoresFile = open("highscores.txt", "w")
for line in scoresList:
scoresFile.write(line + "\n")
scoresFile.close()
#breaks the loop
break
else:
#sets the message as score too low
message = "Score too low! Not updated"
#if the message is blank then the name wasnt found, the file is appended to the end of the file
if message == "":
message = "New score added"
scoresFile = open("highscores.txt", "a")
scoresFile.write(name + str(score) + "\n")
scoresFile.close()
print(message)
以下是如何删除姓名和高分:
结果:
相关问题 更多 >
编程相关推荐