![]() |
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 #): 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
|