替换文本文件中的值

时间:2019-04-18 07:14:53

标签: python

我正在尝试创建一个跟踪玩家高分的功能。该功能应将播放器的最高得分保存在文本文件中。如果在文本文件中找到了玩家的名字,则应该查看新分数是否更高;如果更高,则将新分数替换旧分数。

我尝试使用以下代码进行操作:

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()

预期结果是将旧分数替换为新分数,但是现在它正在创建新分数,有时甚至会在多行中写入相同的高分数。

1 个答案:

答案 0 :(得分:0)

您使用附加选项打开了fout。请使用“ 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")

由于没有scores.txt的示例,所以我无法调试代码。我希望能成功。