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

2024-10-02 00:34:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编程了一个游戏,在这个游戏中,你可以得到玩家的当前分数(分数),然后有一个保存在.txt文档中的最高得分(高分),我需要能够比较这些值,如果分数>高分,我需要能够更新它,我不知道如何更新,任何帮助都将不胜感激。在

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

这是我迄今为止所做的,只是删除了文档中的内容。在


Tags: 文档txt游戏closereadsave编程open
1条回答
网友
1楼 · 发布于 2024-10-02 00:34:31

你只需要一个函数来替换分数。比如:

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(带。。。作为。您也可以read here。在

相关问题 更多 >

    热门问题