gpt4 book ai didi

Python连续写入失败

转载 作者:行者123 更新时间:2023-11-28 22:31:56 25 4
gpt4 key购买 nike

<分区>

我想多次读写文件,但是方法失败,只写入最后一次修改的内容,而不是所有修改的内容。

错误的程序

def openfile():
txt = open("test.txt", "r")
contents = txt.readlines()
txt.close()
return contents

def write_file(contents,f):
old_contents = openfile()
old_contents.insert(1,contents)
contents = "".join(old_contents )
f.write(contents)
f.close()

text1 = open("test.txt","w")
contents= "test1 \n"
write_file(contents,text1)

text2 = open("test.txt","w")
contents = "test2 \n"
write_file(contents,text2)**

担心输出

test2

我希望的输出

test1
test2

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com