繁体   English   中英

在 python 中更新 Txt 文件

[英]Update Txt file in python

我有一个包含名称和结果的文本文件。 如果名称已存在,则只应更新结果。 我尝试使用此代码和许多其他代码,但没有成功。

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

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

PS:我是两周前开始的,所以不要评判我的代码不好。

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)

我建议将 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])

因此,最需要不同的是,当您在 for 循环中说要在新的文本文件中放置一行时,但从未说过要替换分数时不要这样做,所需要的只是下面的 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)

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

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

您在if块内有new_file.write(joined) ,这很好,但在if块外也有new_file.write(line)

if块之外,它将原始行和固定行都放入文件中,并且由于您使用的是write()而不是writelines()两个版本都放在同一行:没有\\n换行符。

您还想添加逗号: joined = ','.join(splitted)因为您在使用line.split(',')line.split(',')了逗号

当我进行这两个修复时,我得到了您似乎期待的结果。

下次你应该包括你期望的输出和你提供的输入。 如果您还包括您实际得到的错误或结果,这可能会有所帮助。

欢迎使用 Python 顺便说一句

从您的代码中删除了问题:

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

    file.close()
    new_file.close()

我相信这是最简单/最直接的做事方式。

代码:

import csv


def update_score(name: str, score: int) -> None:
    with open('../resources/name_data.csv', newline='') as file_obj:
        reader = csv.reader(file_obj)
        data_dict = dict(curr_row for curr_row in reader)

    data_dict[name] = score

    with open('../out/name_data_out.csv', 'w', newline='') as file_obj:
        writer = csv.writer(file_obj)
        writer.writerows(data_dict.items())


update_score('Buddy', 200)

输入文件:

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

输出文件:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM