【问题标题】:Modify list with io module in python在python中使用io模块修改列表
【发布时间】:2021-01-19 22:34:18
【问题描述】:

我试图用 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

【问题讨论】:

    标签: python list module io overwrite


    【解决方案1】:

    替换代码没问题。您必须编辑第 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
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      相关资源
      最近更新 更多