【问题标题】:Insert text in between file lines in python在python的文件行之间插入文本
【发布时间】:2025-12-27 05:55:17
【问题描述】:

我有一个正在读取的文件

fo = open("file.txt", "r")

然后通过做

file = open("newfile.txt", "w")
file.write(fo.read())
file.write("Hello at the end of the file")
fo.close()
file.close()

我基本上是将文件复制到一个新的,但也在新创建的文件末尾添加一些文本。我怎么能插入那条线,说,在由空行分隔的两行之间?即:

line 1 is right here
                        <---- I want to insert here
line 3 is right here

我可以用\n 之类的分隔符来标记不同的句子吗?

【问题讨论】:

    标签: python io insert tokenize writetofile


    【解决方案1】:

    不推荐使用readlines(),因为它将整个文件读入内存。它也不是必需的,因为您可以直接遍历文件。

    以下代码将在第 2 行插入 Hello at line 2

    with open('file.txt', 'r') as f_in:
        with open('file2.txt','w') as f_out:
            for line_no, line in enumerate(f_in, 1):
                if line_no == 2:
                    f_out.write('Hello at line 2\n')
                f_out.write(line)
    

    注意with open('filename','w') as filevar 成语的使用。这消除了对显式 close() 的需求,因为它会在块的末尾自动关闭文件,而且更好的是,它会这样做即使有异常

    【讨论】:

      【解决方案2】:

      对于大文件

      with open ("s.txt","r") as inp,open ("s1.txt","w") as ou:
          for a,d in enumerate(inp.readlines()):
              if a==2:
                  ou.write("hi there\n")
              ou.write(d)
      

      【讨论】:

        【解决方案3】:

        首先您应该使用open() 方法加载文件,然后应用.readlines() 方法,该方法在"\n" 上拆分并返回一个列表,然后通过在两个字符串之间插入一个新字符串来更新字符串列表列表,然后只需使用 new_file.write("\n".join(updated_list)) 将列表的内容写入新文件

        注意:此方法仅适用于可加载到内存中的文件。

        with open("filename.txt", "r") as prev_file, open("new_filename.txt", "w") as new_file:
            prev_contents = prev_file.readlines()
            #Now prev_contents is a list of strings and you may add the new line to this list at any position
            prev_contents.insert(4, "\n This is a new line \n ")
            new_file.write("\n".join(prev_contents))
        

        【讨论】:

        • 如果文件可以完全加载到内存中。
        • @Will,对于非常大的文件,OP 必须 yield 相应地写入内容并写入新文件。