I guess the easiest way to achieve posting a new line with *Title[Name]2 at the end of each *Title region where there at least 5 consecutive lines containing 1 1 1 1 would be vi
You added code in the part which happens when we see a new *Title
line, but of course the counter should be incremented when you are in a region where the current line ends with 1 1 1 1
. Here is a refactoring which moves things around a bit for your new requirement.
transitions = dict()
reg_count = 0
reg_end = -1
current_title = None
with open("test.txt","r") as testfile:
content = testfile.readlines()
for idx, line in enumerate(content):
if line.startswith('*Title '):
current_title = line.rstrip('\n') + '2\n'
elif line.strip().endswith(' 1 1 1 1'):
reg_count += 1
reg_end = idx
elif reg_count:
if current_title and reg_count >= 5:
transitions[reg_end] = current_title
reg_count = 0
if current_title and reg_count >= 5:
transitions[reg_end] = current_title
with open("test.txt", "w") as output:
for idx, line in enumerate(content):
output.write(line)
if idx in transitions:
output.write(transitions[idx])
Demo: https://ideone.com/pJaVvq
If you want to develop this further, add print
statements which show the value of pertinent variables in each section so you can see what's going on when the program processes a simple file. I don't believe you can make meaningful changes to code before you understand how it works.