Insert text in between file lines in python

时间秒杀一切 提交于 2019-12-24 03:29:22

问题


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
                        <---- I want to insert here
line 3 is right here

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


回答1:


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



回答2:


readlines() is not recommended because it reads the whole file into memory. It is also not needed because you can iterate over the file directly.

The following code will insert Hello at line 2 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)

Note the use of the with open('filename','w') as filevar idiom. This removes the need for an explicit close() because it closes the file automatically at the end of the block, and better, it does this even if there is an exception.




回答3:


For Large file

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)


来源:https://stackoverflow.com/questions/31261123/insert-text-in-between-file-lines-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!