Hi everyone. I have question and i hope someone will be pleased to help me. I am trying to write a python script which can extract data from a file (Iter.dat) and then put data in a tableau like the out.dat file. Here is what i wrote:

f = open('Iter.dat', 'r')

print('{:>4}{:>10}{:>8}{:>8}'.format('','canofica','lnvd','msd'))

data = [0, 0, 0]

prev = ""

for line in f:
    a = line.split('/')
    b = a[1].split(':')
    c = b[0].split('.')
    d = b[1].split(' ')
    e = int(b[2])
    if a[0] != prev:
        prev = a[0]
        print('{:>4}{:>10}{:>8}{:>8}'.format(a[0],data[0],data[1],data[2]))
    if c[0] == "canofica":
        data[0] = e
    elif c[0] == "lnvd":
        data[1] = e
    elif c[0] == "msd":
        data[2] = e
f.close()

And this is the result:

    canofica    lnvd     msd
10_2         0       0       0
9_1        14       4      37

which is not quite i expected, which is not like the out.dat. So, can anyone help me please, where did i go wrong? Thanks in advance.

Edited 2 Years Ago by Gribouillis: code formating

Algorithmically, you're reading groups of lines and printing output for this group when it's finished. Pseudo code looks like

current_group = None
for line in file:
    group <- extract group from line
    if group != current_group: # we're starting a new group
        if current_group is not None:
            print current_group output
        current_group <- group
    collect data from line
print current_group output # the last group

Python has also another solution for this problem, which is the itertools.groupby() method. With this tool, code would look like

...
def group_key(line):
    return line.split('/', 1)[0]

for key, group in groupby(f, group_key):
    data = [0,0,0]
    for line in group:
        ... # extract data from line
    ... # print group output

Edited 2 Years Ago by Gribouillis

Thank you Gribouillis. But honestly, i was expecting something more precise and detailed since i showed what i tried to implement...because i do not understand your pseudo code. Thank you anyway.

This article has been dead for over six months. Start a new discussion instead.