【问题标题】:Update Txt file in python在 python 中更新 Txt 文件
【发布时间】:2020-04-14 22:55:56
【问题描述】:

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

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

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

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

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)

【问题讨论】:

  • 但没有成功。你能说得更具体些吗?代码有什么问题?您也没有清楚地解释程序要做什么,这意味着我们都必须尝试从您的代码中猜测。

标签: python python-3.x function


【解决方案1】:

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

【讨论】:

  • 这缺少 csv 导入 eh。此外,您可以调用writer.writerows(d.items()),而不是遍历字典中的每一对。
【解决方案2】:

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

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)

【讨论】:

  • 还修正了一些文字以获得想要的结果,例如 "、".join 和 (joined+'\n')
  • 没有文件的上下文管理器? updatescore 究竟返回了什么?查看OP的数据,逗号后面有一个空格。您拆分 just 逗号,这意味着值前面有一个额外的空格。在这种特殊情况下,这可能不是问题,但可能会出现问题。
  • @AMC 更新分数和逗号分隔不是我的代码,我只是复制了 OP 给出的内容,我明白你在说什么,但除了 OP 要求的结果所需的内容外,我没有做太多改变.如果您想了解有关代码的任何其他信息,您应该询问 OP 以及他/她/他们对代码本身的原因。
【解决方案3】:

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

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

【讨论】:

  • 我相信不鼓励直接退货。你可以使用休息来代替。
  • 在这里使用 break 无效,因为它会执行循环之后的内容!走这条路线需要一个额外的布尔值来检查它是否被添加
  • 一个 break 仍然可以工作,你只需要在循环之后加上一个 else 语句。你能解释一下seek 的用途吗?为什么是 while 循环,for 循环不能完成这项工作?
  • @AMC For 循环不会在这里完成这项工作你可以在这里参考这篇文章stackoverflow.com/a/42150352/8692977 我使用 seek 基本上未读一行以用新行覆盖它。实际上,如果旧分数更长,我只是发现此解决方案存在问题,它不会覆盖整个问题。下班后我会修的!
【解决方案4】:

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

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

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

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

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

欢迎来到 Python 顺便说一句

【讨论】:

    【解决方案5】:

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

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

    【讨论】:

    • 没有上下文管理器?为什么使用.readlines() 而不是直接遍历文件对象?看起来您应该使用 csv 模块。而不是手动拆分和加入。
    • 我的意思是,我认为您还没有发现所有的问题。
    【解决方案6】:

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

    代码:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      相关资源
      最近更新 更多