2015-02-11 22 views
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) 

回答

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]