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()
预期的结果是旧的分数被新的替换,但现在它正在创建新的,有时它甚至在多行中写入相同的高分。
解决方案
您使用附加选项打开了 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 没有示例。我希望这行得通。
推荐阅读
- ffmpeg - 使用 ffmpeg 将视频分割成特定长度
- reactjs - 反应路由器未在生产中加载动态网址
- database - 创建了一个 SQLite 文件,但仍然出现错误:文件不是数据库
- maven - Apache Avro maven 插件似乎忽略了配置
- javascript - 如何使用引导程序制作粘性导航栏?
- laravel - 为 laravel-filemanager 使用 tinymce-vue
- html - 如何查看使用 reactjs 构建的 html 结果
- php - 如何正确地将url存储在数据库中?
- javascript - e.preventDefault() 在 es6 箭头函数循环中不起作用
- python - 有没有办法将python日期中的几个单元格转换为excel日期?