0
我正在爲可以在文本文件中添加/刪除/讀取高分和名稱的程序編寫函數。我有addscore函數工作,但似乎無法解決從文本文件中刪除選定的名稱和高分。這是我如何開始刪除功能,我也有一些其他的代碼,但沒有任何意義。預先感謝您的任何幫助。使用python從文件中刪除文本
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)