简体   繁体   中英

Replacing value in a text file

I'm trying to make a function that keeps track of players' high scores. The function should save the highest score of the player in the text file. If a player's name is found in the text file it should look if the new score is higher, if it's higher it will replace the old score with new.

I've tried to do it with following code:

f1 = open('scores.txt', 'r')
f2 = open('scores.txt', 'a')

if f1.read() == "":  #if txt.file is empty, add the name and highscore directly
    f2.write(self.name)
    f2.write(";")
    f2.write('%d' % self.highscore)
    f2.write("\n")

else: #if not empty...
    with open("scores.txt", "r") as fin:
        with open("scores.txt", "a") as fout:
            for line in fin:
                fields = line.strip(";")
                if fields[0].lower() == self.name.lower(): #look if the players name is in textfile.
                    if int(fields[1]) < self.highscore: #if new score is higher, replace the old with it.
                        fout.write(line.replace(str(fields[1]), str(self.highscore)))
                        break
                    else:
                        pass
                else: #if name not found in file, create new line.
                    fout.write(self.name)
                    fout.write(";")
                    fout.write('%d' % self.highscore)
                    fout.write("\n")
f1.close()
f2.close()

The expected result is that the old score is replaced with new, but now it is creating new, and sometimes it even writes the same high score in multiple lines.

You opened fout with append option. Please change it with write like "w+"

 else: #if not empty...
    with open("scores.txt", "r") as fin:
        with open("scores.txt", "w+") as fout:
            for line in fin:
                fields = line.strip(";")
                if fields[0].lower() == self.name.lower(): #look if the players name is in textfile.
                    if int(fields[1]) < self.highscore: #if new score is higher, replace the old with it.
                        fout.write(line.replace(str(fields[1]), str(self.highscore)))
                        break
                    else:
                        pass
                else: #if name not found in file, create new line.
                    fout.write(self.name)
                    fout.write(";")
                    fout.write('%d' % self.highscore)
                    fout.write("\n")

I couldn't debug the code since there is no sample for scores.txt. I hope that's worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM