我正在编写一个程序函数,可以在文本文件中添加/删除/读取高分和名称。我有addscore功能工作,但似乎无法弄清楚从文本文件中删除选定的名称和高分。这是我开始删除功能的方式,我也有一些其他代码,但没有一个是有意义的。预先感谢您的任何帮助。
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)
答案 0 :(得分:1)
以下是删除名称和高分的方法:
def deletescore(name, newscore):
names = ['Alex', 'Jason', 'Will', 'Jon']
scores = [10, 88, 55, 95]
scores.append(newscore)
names.remove(name)
scores = sorted(scores, reverse=True)
scores.remove(scores[0])
print names
print scores
deletescore('Jason',94)
结果:
['Alex', 'Will', 'Jon']
[94, 88, 55, 10]