Python Forum

Full Version: Add new line after finding last string in a region
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!

  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