python在txt文件中添加内容,在python中的文件行之间插入文本

I have a file that I am currently reading from using

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

Then by doing

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

line 3 is right here

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

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值