用python更新Txt文件

2024-09-27 00:16:04 发布

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

我有一个包含名字和结果的文本文件。如果名称已存在,则只应更新结果。我尝试了这个代码和其他许多代码,但没有成功。你知道吗

文本文件的内容如下所示:

Ann, 200
Buddy, 10
Mark, 180
Luis, 100

附言:我两周前就开始了,所以不要评判我的错误代码。你知道吗

from os import rename


def updatescore(username, score):
    file = open("mynewscores.txt", "r")
    new_file = open("mynewscores2.txt", "w")
    for line in file:
        if username in line:
            splitted = line.split(",")
            splitted[1] = score
            joined = "".join(splitted)
            new_file.write(joined)
        new_file.write(line)
    file.close()
    new_file.close()


maks = updatescore("Buddy", "200")
print(maks)

Tags: 代码intxtnewlineusernameopenfile
3条回答

所以最需要区别的是,在for循环中,你说要在新的文本文件中放一行,但从来没有说过要在想要替换分数时不这样做,所需要的只是if语句下面的else语句:

from os import rename


def updatescore(username, score):
    file = open("mynewscores.txt", "r")
    new_file = open("mynewscores2.txt", "w")
    for line in file:
        if username in line:
            splitted = line.split(",")
            splitted[1] = score
            print (splitted)
            joined = ", ".join(splitted)
            print(joined)
            new_file.write(joined+'\n')
        else:
            new_file.write(line)



    file.close()
    new_file.close()


maks = updatescore("Buddy", "200")
print(maks)

我建议将csv作为字典读入,只更新一个值。你知道吗

import csv
d = {}
with open('test.txt', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
            key,value = row
            d[key] = value

d['Buddy'] = 200

with open('test2.txt','w', newline='') as f:
    writer = csv.writer(f)
    for key, value in d.items():
            writer.writerow([key,value])

你可以试试这个,如果用户名不存在就添加,否则就更新它。你知道吗

def updatescore(username, score):
    with open("mynewscores.txt", "r+") as file:
        line = file.readline()
        while line:
            if username in line:
                file.seek(file.tell() - len(line))
                file.write(f"{username}, {score}")
                return
            line = file.readline()
        file.write(f"\n{username}, {score}")

maks = updatescore("Buddy", "300")
maks = updatescore("Mario", "50")

相关问题 更多 >

    热门问题