collecting data from file

Don Arnold dlarnold at west.com
Fri Apr 11 09:39:19 EDT 2003


Jeremy Yallop <jeremy at jdyallop.freeserve.co.uk> wrote in message news:<slrnb9d2sh.1oq.jeremy at saturn.cps.co.uk>...
> Mustafa Celik wrote:
> > I want to scroll thru a file;
> >    * find lines that match a string (e.g. HELLO) on the 2nd column
> >    * add up the 4th column (an integer) on each matching line, say the 
> > variable is TOTAL
> >    * subtract the 4th column from TOTAL if another is string (e.g. BYE) 
> > is hit on 2nd column of a line
> 
> I'd use awk for this.
> 
>   { 
>     if ($2 == "HELLO")    { total += $4 }
>     else if ($2 == "BYE") { total -= $4 }
>   }
>   END { print total }
> 
> Jeremy.

Last time I checked, this was the Python newsgroup, so I think a
solution _in_ Python is more appropriate:

total = 0
infile = open('c:/temp2/input.txt')

for line in infile.readlines():
    line_items = line.split()
    if len(line_items) >= 4:
        print '[%s]' % line_items
        tag = line_items[1]
        amt = float(line_items[3])
            
        if tag == 'HELLO':
            print 'adding', amt, '...'
            total += amt
        elif tag == 'BYE':
            print 'subtracting', amt, '...'
            total -= amt
        print 'total:', total

---- output: ----

[['0', 'HELLO', 'stuff', '5']]
adding 5.0 ...
total: 5.0
[['1', 'HELLO', 'stuff', '3']]
adding 3.0 ...
total: 8.0
[['2', 'BYE', 'stuff', '2']]
subtracting 2.0 ...
total: 6.0
[['3', 'HELLO', 'stuff', '4']]
adding 4.0 ...
total: 10.0
[['4', 'BYE', 'stuff', '5']]
subtracting 5.0 ...
total: 5.0
[['5', 'HELLO', 'stuff', '2']]
adding 2.0 ...
total: 7.0
[['6', 'BYE', 'stuff', '1']]
subtracting 1.0 ...
total: 6.0
[['7', 'HELLO', 'stuff', '5']]
adding 5.0 ...
total: 11.0
[['8', 'BYE', 'stuff', '10']]
subtracting 10.0 ...
total: 1.0

HTH,
Don




More information about the Python-list mailing list