开发者

Help writing the output to another file:

开发者 https://www.devze.com 2023-01-16 02:02 出处:网络
Hi here is the program I have: with open(\'C://avy.txt\', \"rtU\") as f: columns = f.readline().strip().split(\" \")

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))
0

精彩评论

暂无评论...
验证码 换一张
取 消