在 Python 中,如何使用函数将文本文件中的值替换为该值的新更新版本?

In Python how can I replace a value in a text file with a new updated version of that value using a function?

我编写了一个游戏,您可以在其中获得玩家的当前分数 (score),然后将获得的最高分数 (high_score) 保存在 .txt 文档中,我需要为了能够比较这些值,如果分数 > high_score,我需要能够更新它,但我不知道如何更新,感谢任何帮助。

file = open('save.txt','r+')
saved = file.read()
file.close()

high_score = saved
high_score = int(high_score)
global score
score = 21

def checkscore():
    if score > high_score:
        file = open('save.txt' , 'w+')
        file.write(file.read().replace(saved,str(score)))
        file.close()
    else:
        file.close()
    return

checkscore()

这是我到目前为止尝试过的方法,似乎只是删除了文档中的内容。

你只需要一个函数,在需要的时候替换乐谱。类似于:

def update_score(new_score, file_name="save.txt"):
    with open(file_name,'r+') as saved_file:
        existing_score = int(saved_file.read())
    if new_score > existing_score:
        # replace existing score
        with open(file_name,'w') as saved_file:
            saved_file.write(str(new_score))

编辑: 它使用 context manager (with ... as ...). You can also read here.