Evaluating the next line in a For Loop while in the current iteration
<p>Here is what I am trying to do:
I am trying to solve an issue that has to do with wrapping in a text file. </p>

<p>I want to open a txt file, read a line and if the line contains what I want it to contain, check the next line to see if it does not contain what is in the first line. If it does not, add the line to the first line.</p>

<pre><code>    import re

    stuff = open("my file")

    for line in stuff:
        if re.search("From ", line):
            first = line
            print first
            if re.search('From ', handle.next()):
               continue
            else: first = first + handle.next()

        else: continue
</code></pre>

<p>I have looked a quite a few things and cannot seem to find an answer. Please help!</p>

<p>I would try to do something like this, but this is invalid for triples of "From " and not elegant at all.</p>

<pre><code>lines = open("file", 'r').readlines()
lines2 = open("file2", 'w')    

counter_list=[]
last_from = 0
for counter, line in enumerate(lines):
    if "From " in line and counter != last_from +1:
       last_from = counter
       current_count = counter
    if current_count+1 == counter:
       if "From " in line:
           counter_list.append(current_count+1)

for counter, line in enumerate(lines):
    if counter in counter_list:
        lines2.write(line)
    else:
        lines2.write(line, '\n')
</code></pre>

<p>Than you can check the lines2 if its helped.</p>

<p>You could also revert order of lines, then check in next line not in previous. That would solve your problem in one loop.</p>

python python-2.7