繁体   English   中英

替换文本文件中的值

[英]Replacing value in a text file

我正在尝试制作一个跟踪玩家高分的功能。 该函数应将玩家的最高分保存在文本文件中。 如果在文本文件中找到玩家的名字,它应该查看新分数是否更高,如果更高,它将用新分数替换旧分数。

我尝试使用以下代码来做到这一点:

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

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

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

我无法调试代码,因为没有 score.txt 的示例。 我希望这奏效了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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