我试图用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 texttxt文件在之后
Modified
second line of text
third line of text
fourth line of text
of text发布于 2020-10-05 04:10:59
替换代码没问题。你必须编辑第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.closehttps://stackoverflow.com/questions/64202206
复制相似问题