Python Forum

Full Version: Add a line after a specific line
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.
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 ?
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')