在python中的文件行之间插入文本 [英] Insert text in between file lines in python

查看:794
本文介绍了在python中的文件行之间插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目前正在阅读的文件

I have a file that I am currently reading from using

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()

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

I basically copy the file to a new one, but also add some text at the end of the newly created file. How would I be able to insert that line say, in between two lines separated by an empty line? I.e:

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

我可以通过像这样的分隔符来标记不同的句子吗? \\ n for new line?

Can I tokenize different sentences by a delimiter like \n for new line?

推荐答案

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

First you should load the file using the open() method and then apply the .readlines() method, which splits on "\n" and returns a list, then you update the list of strings by inserting a new string in between the list, then simply write the contents of the list to the new file using the new_file.write("\n".join(updated_list))

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

NOTE: This method will only work for files which can be loaded in the memory.

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))

这篇关于在python中的文件行之间插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆