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

Modify list with io module in python

我正在尝试用 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