An elegant, readable way to read Butcher tableau from a file
Question: I'm trying to read a specifically formatted file (namely, the Butcher tableau)
in python 3.5. The file looks like this(tab separated):

    
    
    S
    a1  b11  b12  ... b1S
    a2  b21  b22  ... b2S
    ...
    aS  bS1  bS2  ... bSS
    0.0 c1   c2   ... cS
    [tolerance]
    

for example, (tab separated)

    
    
    2
    0.0 0.0 0.0
    1.0 0.5 0.5
    0.0 0.5 0.5
    0.0001
    

So my code looks like i'm writing in C. Is there a more pythonic approach to
parsing this file? Maybe there are numpy methods that could be used here?

    
    
    #the data from .dat file
    S = 0    #method order, first char in .dat file
    a = []   #S-dim left column of buther tableau
    b = []   #S-dim matrix
    c = []   #S-dim lower row
    tolerance = 0 # for implicit methods
    
    def parse_method(file_name):
        'read the file_name, process lines, produce a Method object'
        try:
            with open('methods\\' + file_name) as file:
                global S
                S = int(next(file))
                temp = []
                for line in file:
                    temp.append([float(x) for x in line.replace('\n', '').split('\t')])
            for i in range(S):
                a.append(temp[i].pop(0))
                b.append(temp[i])
            global c
            c = temp[S][1:]
            global tolerance
            tolerance = temp[-1][0] if len(temp)>S+1 else 0
        except OSError as ioerror:
            print('File Error: ' + str(ioerror))
    


Answer: Code -

    
    
    from collections import namedtuple
    
    
    def parse_file(file_name):
        with open('a.txt', 'r') as f:
            file_content = f.readlines()
        file_content = [line.strip('\n') for line in file_content]
        s = int(file_content[0])
        a = [float(file_content[i].split()[0]) for i in range(1, s + 1)]
        b = [list(map(float, file_content[i].split()[1:]))
             for i in range(1, s + 1)]
        c = list(map(float, file_content[-2].split()))
        tolerance = float(file_content[-1])
        ButcherTableau = namedtuple('ButcherTableau', 's a b c tolerance')
        bt = ButcherTableau(s, a, b, c, tolerance)
        return bt
    
    p = parse_file('a.txt')
    
    print('S :', p.s)
    print('a :', p.a)
    print('b :', p.b)
    print('c :', p.c)
    print('tolerance :', p.tolerance)
    

Output -

    
    
    S : 2
    a : [0.0, 1.0]
    b : [[0.0, 0.0], [0.5, 0.5]]
    c : [0.0, 0.5, 0.5]
    tolerance : 0.0001
    

