Python Forum
Add a line after a specific line - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Add a line after a specific line (/thread-12064.html)



Add a line after a specific line - morgandebray - Aug-07-2018

Hi, I'm trying to add new line after a particular line.

for line in file :
   if line.startswith('/22/'):
            #ADD LINE AFTER THIS line
            #WITH "TEST" AS CONTENT
but file.write("TEST") add a line at the end of the file
I want the "TEST" line to be added after the "/22/" line


RE: Add a line after a specific line - buran - Aug-07-2018

you cannot insert it in the middle.
you need to create new/different file and write in it.
or read everything in the memory (incl. the new lines) and then overwrite the existing file.


RE: Add a line after a specific line - morgandebray - Aug-07-2018

This sounds complicated, no ?
I have to insert line in different place in the same file, I would need to create like 4 files to add 4 lines ?


RE: Add a line after a specific line - buran - Aug-07-2018

No, you need to create one extra file

input_file = 'input_file.txt' # '/path/to/inputfile.txt'
output_file = 'output_file.txt' # '/path/to/outputfile.txt'

with open(input_file) as in_file, open(output_file, 'w') as out_file:
    for line in in_file:
        out_file.write(line)
        if line.strip() == '/##/':
            out_file.write('TEST INSERT OF NEW LINE\n')