【发布时间】: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