Reading repeated information from the file in different order in Python
<p>I tried to search for similar questions, but I couldn't find. Please mark as a duplicate if there is similar questions available.</p>

<p>I'm trying to figure out a way to read and gather multiple information from single file. Here in the file Block-A,B &amp; C are repeated in random order and Block-C has more than one information to capture. Every block end with 'END' text. Here is the input file:</p>

<pre><code>Block-A:
(info1)
END
Block-B:
(info2)
END
Block-C:
(info3)
(info4)
END

Block-C:
(info7)
(info8)
END
Block-A:
(info5)
END
Block-B:
(info6)
END
</code></pre>

<p>Here is my code:</p>

<pre><code>import re
out1 = out2 = out3 = ""
a = b = c = False
array=[]

with open('test.txt', 'r') as f:

    for line in f:
        if line.startswith('Block-A'):
            line = next(f)
            out1 = line
            a = True
        if line.startswith('Block-B'):
            line=next(f)
            out2 = line
            b = True
        if line.startswith('Block-C'):
            c = True

        if c:
            line=next(f)
            if not line.startswith('END\n'):
                out3 = line
                array.append(out3.strip())

        if a == b == c == True:
            print(out1.rstrip() +', ' + out2.rstrip() + ', ' + str(array))
            a = b = c = False
            array=[]
</code></pre>

<p>Thank you in advance for your valuable inputs.</p>

<p>If you don't want the Block-X to print, unhash the elif statment</p>

<pre><code>import os
data = r'/home/x/Desktop/test'

txt = open(data, 'r')

for line in txt.readlines():
    line = line[:-1]
    if line in ('END'):
        pass
    #elif line.startswith('Block'):
       # pass
    else:
        print line
&gt;&gt;&gt;&gt;
Block-A:
(info1)
Block-B:
(info2)
Block-C:
(info3)
(info4)
Block-C:
(info7)
(info8)
Block-A:
(info5)
Block-B:
(info6)
</code></pre>

python readfile