Python Forum
Add new line after finding last string in a region - 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 new line after finding last string in a region (/thread-28890.html)



Add new line after finding last string in a region - Nigel11 - Aug-08-2020

Hello

I have this input .txt file (a demo of it here, on a small scale) that after running the Python 3.6 code it should write in the input the following output (please see the output interleaved with #):

Output:
Noclue *Title Test 12125 124125 asdas 1 1 1 1 rthtr 1 1 1 1 asdasf 1 1 1 1 asfasf 1 1 1 1 blabla 1 1 1 1 #Expected "*Title Test2" here 124124124 *Title Dunno 12125 124125 12763125 1 1 1 1 whatever 1 1 1 1 #Expected "*Title Dunno2" here 214142122 #and so on for thousands of them..
I have this code, that I have to adapt:

index = 0
insert = False
currentTitle = ""
testfile = open("test.txt","r")    
content = testfile.readlines()
finalContent = content
testfile.close()
# Should change the below line of code I guess to adapt
#titles = ["TitleX","TitleY","TitleZ"]   

for line in content:
    index = index + 1
    for title in titles:
        if line in title+"\n":    
            currentTitle = line
            print (line)
    if line == "1 1 1 1\n":
        insert = True
    if (insert == True) and (line != "1 1 1 1\n"):
        finalContent.insert(index-1, currentTitle[:6] + "2" + currentTitle[6:])
        insert = False

f = open("test.txt", "w")
finalContent = "".join(finalContent)
f.write(finalContent)
f.close()
Any help on how to adapt the above code to display the desired output would be more than appreciated!
Thanks!


RE: Add new line after finding last string in a region - Larz60+ - Aug-08-2020


  1. read input line
  2. write line to output
  3. If this is target line, write new data
  4. Continue loop at step 1 until finished, but eliminate step 3