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(val开发者_StackOverflow中文版ues)):
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
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.
out = open('Finished', 'w')
for index, summedRowValue in enumerate(sums):
out.write('%s %f\n' % (columns[index], 1.0 * summedRowValue / numRows))
精彩评论