I need to read input from a text file and create a new text file with the output in it. At the moment my code is reading fine but it is writing only the last line of data, not going through all the lines. Can someone please help me fix this?
def generate_daily_totals(input_filename, output_filename):
"""Returns date followed by the sum of values"""
infile = open(input_filename)
for line in infile:
content = line.split(",")
date = content[0]
total = 0
for value in content[1:]:
total = total + float(value)
rounded_total = "{:.2f}".format(total)
summary = date + " " + "=" + " " + rounded_total
outfile = open(output_filename, "w")
outfile.write(summary)
generate_daily_totals('data60.txt', 'totals60.txt')
checker = open('totals60.txt')
print(checker.read())
checker.close()
The input is
2006-04-10,836.2,563.263
2006-04-10,462.06,1694.3,666.0
2006-04-10,1318.19,1485.62
2006-04-10,49.714,304.0,1269.0
2006-04-10,1360.0,1731.0,28.6
2006-04-10,998.879,890.264,367.0
2006-04-10,757.4,1501.05,861.6
2006-04-10,1218.0,270.0
What I am getting for output is
2006-04-10 = 1488.00
But the correct one should be
2006-04-10 = 1399.46
2006-04-10 = 2822.36
2006-04-10 = 2803.81
2006-04-10 = 1622.71
2006-04-10 = 3119.60
2006-04-10 = 2256.14
2006-04-10 = 3120.05
2006-04-10 = 1488.00