使用python中的io模块修改列表

问题描述

我正在尝试使用io模块覆盖一行文本,问题是当我运行脚本并检查.txt时,除文件末尾外,覆盖的行都很好。

from io import open

text = open("tst.txt","r+")
list_j = text.readlines()
list_j[0] = "Modified\n"
text.seek(0)
text.writelines(list_j)
text.close

之前的txt文件

first line of text
second line of text
third line of text
fourth line of text

之后的txt文件

Modified
second line of text
third line of text
fourth line of text
 of text

解决方法

可以使用替换代码。您必须编辑第9行以将其正确写入文件。

from io import open

text = open("tst.txt","r+")
list_j = text.readlines()
list_j[0] = "Modified\n"
text.seek(0)
#text.writelines(list_j)
with open('tst.txt','w+') as the_file:
    for x in list_j:
        the_file.write(x)
text.close