jburke424
jburke424

Reputation: 1

Deleting text from file using python

I am writing a function for a program that can add/delete/read highscores and names within a text file. I have the addscore function working but cant seem to figure out about deleting a selected name and highscore from the text file. This is how i have started the delete function, i had some other code too but none of it made sense. Thank you in advance for any help.

import os
def deleteScore():
    nameDelete = input("Enter a name you would like to delete... ")
    deleteFile = open("highscores.txt", "r")
    deleteList = deleteFile.readlines()
    deleteFile.close()

this is also the addscore function which is working perfectly and write to the text file in the format :

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)

Upvotes: 0

Views: 124

Answers (1)

Jonathan Epstein
Jonathan Epstein

Reputation: 379

Here's how to delete a name and highscore:

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)

results:

['Alex', 'Will', 'Jon']
[94, 88, 55, 10]

Upvotes: 1

Related Questions