替换文本文件中的值 Python

Replace value in text file Python

我想检查文本文件中的分数值,如果给定名称的分数值小于新分数,则更新它。
我有以下文本文件:

Harry White,8
William Ross,9
Ron Weasley,10

现在,我有以下功能:

def set_score(name,score):
    s = open('sc.txt','r+')
    scorelist = s.readlines()
    present=False
    for i in scorelist:
        check  = i.split(',')[0]       
        
        if(check==name):
            present=True
            score1= i.rstrip('\n').split(',')[1]
            if(score1<score):
                
                i.replace(score,score1)
            break;
    
    if(present==False):
        s.write(name+","+score)
                
            
    s.close()
    
set_score("William Ross","10")

它不更新值。为什么?
我检查了,if 条件是 运行 但 replace 语句不起作用。

因为该名称已经存在于文件中,而您的代码只有 write 秒,但实际上没有。

如果你想在文件名出现时更改文件,在这种情况下你也需要 write 文件(更改字符串不会影响文件,因为你已经找到)。

您不能更改迭代器本身,但这就是您正在做的事情:

for i in scorelist:
(...)           
                i.replace(score, score1)

试试这个:

for ix, i in enumerate(scorelist):
(...)           
                scorelist[ix].replace(score, score1)

不一定最有效但可能更清晰。

打开文件进行阅读并将其内容加载到字典中。

如果字典里有这个名字,比较分数。如果新分数大于旧分数,则更新字典。

打开要写入的文件并将更新后的词典内容转储到其中。

FILENAME='sc.txt'

def set_score(name, score):
    d = dict()
    with open(FILENAME) as sf:
        for line in map(str.strip, sf):
            ns, cs = line.split(',')
            d[ns] = int(cs)
    if (old_score := d.get(name)) is None or old_score < score:
        d[name] = score
        with open(FILENAME, 'w') as sf:
            for k, v in d.items():
                print(f'{k},{v}', file=sf)

set_score('William Ross', 10)

请注意,如果需要更改,文件只是 re-opened(用于写入)

编辑:

从其他地方的评论看来,如果文件中不存在该名称,则应添加该名称。逻辑相应改变