4

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?

Falko
  • 17,076
  • 13
  • 60
  • 105
L0g1x
  • 66
  • 1
  • 6

4 Answers4

6

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))
ZdaR
  • 22,343
  • 7
  • 66
  • 87
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.

SiHa
  • 7,830
  • 13
  • 34
  • 43
0

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)
The6thSense
  • 8,103
  • 8
  • 31
  • 65
0

U could use a marker

#FILE1
line 1 is right here
<INSERT_HERE>                  
line 3 is right here
#FILE2
some text
with open("FILE1") as file: 
    original = file.read()
with open("FILE2") as input:
    myinsert = input.read()

newfile = orginal.replace("<INSERT_HERE>", myinsert)

with open("FILE1", "w") as replaced:
    replaced.write(newfile)
#FILE1
line 1 is right here
some text                
line 3 is right here
codetiger
  • 2,650
  • 20
  • 37
maniac
  • 3
  • 2