[英]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.