collecting data from file
Terry Reedy
tjreedy at udel.edu
Fri Apr 11 09:33:15 EDT 2003
"Peter Hansen" <peter at engcorp.com> wrote in message
news:3E96B6BC.E9DBE74F at engcorp.com...
> 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
> >
> > Any tips?
>
> Yes, post an example showing what you intend. The instructions are
> decent, but implementable only by making a few assumptions about
what
> you mean.
In particular, how are the 'columns' specified. Your examples imply
that you mean variable-length data fields rather than character
columns. If so, are they separated by <space>, <tab>, a mixture of
the two, <comma>, or something else.
> Also, are there any error conditions to be handled, or do
> you guarantee the input is always perfect (e.g., always at least
four
> columns, and so on)?
Missing data is the great bugaboo of data analysis. Ignoring that
possibility
sum = 0
for line in file('mydata'):
fields = line.split() # assume whitespace
if field[1] == 'HELLO':
sum += field[3]
elif field[1] == 'BYE'
sum += field[3]
Terry J. Reedy
More information about the Python-list
mailing list