【问题标题】:How to append to a specific line in python without overwriting如何在不覆盖的情况下附加到python中的特定行
【发布时间】:2021-12-12 19:51:29
【问题描述】:

我正在尝试通过检查文件的第一个值来追加到文件中的特定行。

deposit = str(deposit)
with open('Customer Statements.txt','r+') as a:
    lines = a.readlines()

    for i,line in enumerate(lines):
        if line.startswith(loginDetails):
            trans = ('{}/Deposit|{}'.format(dt,deposit))
    with open('Customer Statements.txt','a') as a:
        a.seek(0)
        for line in lines:
            a.write(line)
            break

请帮忙!这是我试图让它工作但徒劳的代码

【问题讨论】:

  • stackoverflow.com/questions/22779650/…:就目前而言,trans = ('{}/Deposit|{}'.format(dt,deposit)) 创建了一个新变量 trans,然后什么也不做。也许你想要lines[i] = <updated line contents>?您也不应该使用with open('Customer Statements.txt','a') as a: 重新打开您的文件,如链接所示。
  • 那我如何追加而不是写入?
  • 您已经在代码末尾执行了该操作。第一次打开文件时,您将其打开为“r+”(读取 写入),然后读取每一行文本 (a.readlines())。最后,当您调用a.seek(0) 时,您将光标移回文件的开头,然后循环重新写入每一行。本质上,您正在加载整个文件,修改您想要的行(这是追加发生的地方),然后再次重写所有这些,您只需要为此打开文件一次。
  • 但是当我运行它时,它会覆盖指定行中的最后一个值
  • 谁能帮忙

标签: python-3.x


【解决方案1】:

你在寻找“a”,追加模式吗?

代码:

with open("file", "a") as f:
    f.write("text")

将在文件“file”的末尾附加字符串“text”,而不删除文件的当前内容。

在你的情况下,你可能想要接近:

with open('Customer Statements.txt','a') as a:
    a.write(deposit)

【讨论】:

  • 什么意思?我想追加到特定行的末尾
  • 我还是个初学者,但我迫切需要这个解决方案
  • 是的,我想追加,但对于以用户输入值开头的特定行
猜你喜欢
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 2021-06-15
  • 2015-10-11
  • 2021-03-15
  • 2020-08-30
相关资源
最近更新 更多