Mostly Linux & Python syntax notes and hyperlinks.

Tuesday, June 8, 2010

python: take the average of a column of numbers from a file

Could use smoothing out, but easier than getting out the calculator:
def average(infile):
  acount=0
  asum=0
  f=open(infile,"r")
  g=open("avg_"+infile,"w")
  for line in f:
      num=float(line.strip())
      asum= asum + num
      acount=acount+1
      g.write('count=%d,' % acount)
      g.write('num=%f' %  num )
      g.write(',sum=%f \n' % asum)
  if acount > 0:
     average=asum/acount
     g.write('\n sum=%f \n' % asum )
     g.write('average=%f\n' % average)
  f.close();
  g.close();

def main(infile):
    average(infile)

if __name__ == "__main__":
    import sys
    main(*sys.argv[1:])

Note that float() of blank returns zero, so make sure there's no blank line at the end of your input file. Or, improve the script to check for that sort of thing.
>>> float()
0.0
>>> float( )
0.0
>>>

No comments:

Post a Comment