tags:

views:

48

answers:

2

Hi here is the program I have:

with open('C://avy.txt', "rtU") as f:
    columns = f.readline().strip().split(" ")
    numRows = 0
    sums = [0] * len(columns)

    for line in f:
        # Skip empty lines
        if not line.strip():
            continue

        values = line.split(" ")
        for i in xrange(len(values)):
            sums[i] += int(values[i])
        numRows += 1

    for index, summedRowValue in enumerate(sums):
        print columns[index], 1.0 * summedRowValue / numRows

I'd like to modify it so that it writes the output to a file called Finished. I keep getting errors when I rewrite. Can someone help please?

Thanks

A: 
out = open('Finished', 'w')
for index, summedRowValue in enumerate(sums):
    out.write('%s %f\n' % (columns[index], 1.0 * summedRowValue / numRows))
jcubic
@jcubic, this writes one single, large line to `Finished` -- I think you probably forgot a `\n` somewhere. Which is part of why in my answer I recommend, instead, using the `print>>` form, which offers all of `print`'s usual amenities (automatic stringification and space-separation of fields, automatic line-ends), and just does it on a different open file object instead of the default (standard output AKA `sys.stdout`).
Alex Martelli
Yes I forget that.
jcubic
+1  A: 

Change the snippet which now reads:

 for index, summedRowValue in enumerate(sums):
        print columns[index], 1.0 * summedRowValue / numRows

to make it, instead:

 with open('Finished', 'w') as ouf:
     for index, summedRowValue in enumerate(sums):
         print>>ouf, columns[index], 1.0 * summedRowValue / numRows

As you see, it's very easy: you just need to nest the loop in another with statement (to insure proper opening and closing of the output file), and change the bare print to print>>ouf, to instruct print to use open file object ouf instead of standard-output.

Alex Martelli
Wow! neat trick w/ the 'print>>'
fseto
@fseto, I actually think it's somewhat weird syntax, but the functionality it produces sure does help -- In python 3.any, or 2.6/2.7 with a `from __future__ import print_function`, `print(columns[index], 1.0*summedRowValue/numRows, file=ouf)` gets the same functionality with more sane syntax;-).
Alex Martelli