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
  Βad Input on line 12 Azdaghost 5 1,210 Apr-19-2025, 10:22 PM
Last Post: Azdaghost
Question [SOLVED] [Beautiful Soup] Move line to top in HTML head? Winfried 0 263 Apr-13-2025, 05:50 AM
Last Post: Winfried
  Insert command line in script lif 4 985 Mar-24-2025, 10:30 PM
Last Post: lif
  Entry field random pull from list, each return own line Bear1981 6 796 Feb-25-2025, 06:09 AM
Last Post: Pedroski55
  How to revert back to a previous line from user input Sharkenn64u 2 942 Dec-28-2024, 08:02 AM
Last Post: Pedroski55
  Pandas - error when running Pycharm, but works on cmd line zxcv101 2 2,425 Sep-09-2024, 08:03 AM
Last Post: pinkang
  Simplest way to run external command line app with parameters? Winfried 2 1,242 Aug-19-2024, 03:11 PM
Last Post: snippsat
  Printing the code line number arbiel 6 1,632 Jun-30-2024, 08:01 AM
Last Post: arbiel
  How to add multi-line comment section? Winfried 2 1,366 Jun-04-2024, 07:24 AM
Last Post: Gribouillis
Information Is it possible to multi line a Basic Function Construct line statement? If so how? BrandonKastning 7 1,896 May-23-2024, 03:02 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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