Read block Text of a text file python
<p><strong>Input File - input.csv</strong></p>

<pre><code>#######A Result:#########
2016-07-27   bar       51     14
2015-06-27   roujri    30     86
#######B Result:#########
2016-08-26   foo       34      83
2016-08-26   foo       34      83
#########################
</code></pre>

<p><strong>Output result</strong> </p>

<pre><code>A result:
     Col-1: 81
     Col-2: 100
B result:
     Col-1: 68
     Col-2: 166
</code></pre>

<p>I am trying to solve one problem according to above input, output. So far I can read only first block Text. I want to more generic function so possibly I will only initialise the variable that need to read within the block, not hard coding (e.g. <code>#######A Result:#########</code>) and furthermore pass the block info to another function that will sum up the value. Any suggestion will be greatly appreciate. Thanks :)  </p>

<pre><code>import re
def reading_block_text_file(infile):
     with open(infile) as fp:
         for result in re.findall('#######A Result:#########(.*?)#######B Result:#########', fp.read(), re.S):
             print result,

reading_block_text_file(input_file)
</code></pre>

<p>Throw in a little bit of regex:</p>

<pre><code>$ cat a
#######A Result:#########
2016-07-27   bar       51     14
2015-06-27   roujri    30     86
#######B Result:#########
2016-08-26   foo       34      83
2016-08-26   foo       34      83
#########################
$ cat a.py
import re
col_names = ['abc', 'xyz']
with open("/tmp/a", "r") as f:
    tables = re.findall(r'#+(\w+ Result:)#+([^#]*)', f.read(), re.S)
    for table in tables:
        name = table[0]
        rows = table[1].strip().split('\n')
        print name
        for i in range(len(col_names)):
            print "\t{}: {}".format(col_names[i], sum(map(lambda x: int(x.split()[i + 2]), rows)))
$ python a.py
A Result:
    abc: 81
    xyz: 100
B Result:
    abc: 68
    xyz: 166
</code></pre>

<p>Regex Explanation:</p>

<pre><code>#+(\w+ Result:)#+([^#]*)
</code></pre>

<p><img src="https://www.debuggex.com/i/Bito9rGLY6SLIMCx.png" alt="Regular expression visualization"></p>

<p><a href="https://www.debuggex.com/r/Bito9rGLY6SLIMCx" rel="nofollow">Debuggex Demo</a></p>

python file text block