Python Forum
Add a line after a specific line
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add a line after a specific line
#1
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
Reply
#2
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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 ?
Reply
#4
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')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Line graph with two superimposed lines sawtooth500 4 346 Apr-02-2024, 08:56 PM
Last Post: sawtooth500
  How to add multi-line comment section? Winfried 1 216 Mar-24-2024, 04:34 PM
Last Post: deanhystad
  break print_format lengthy line akbarza 4 383 Mar-13-2024, 08:35 AM
Last Post: akbarza
  Reading and storing a line of output from pexpect child eagerissac 1 4,271 Feb-20-2024, 05:51 AM
Last Post: ayoshittu
  coma separator is printed on a new line for some reason tester_V 4 495 Feb-02-2024, 06:06 PM
Last Post: tester_V
  problem with spliting line in print akbarza 3 394 Jan-23-2024, 04:11 PM
Last Post: deanhystad
  Unable to understand the meaning of the line of code. jahuja73 0 309 Jan-23-2024, 05:09 AM
Last Post: jahuja73
  Receive Input on Same Line? johnywhy 8 729 Jan-16-2024, 03:45 AM
Last Post: johnywhy
  Reading in of line not working? garynewport 2 852 Sep-19-2023, 02:22 PM
Last Post: snippsat
  'answers 2' is not defined on line 27 0814uu 4 743 Sep-02-2023, 11:02 PM
Last Post: 0814uu

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020