Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Help on python Python def append_total (filename): Given a string filename of a

ID: 3818599 • Letter: H

Question

Help on python

Python def append_total (filename): Given a string filename of a file containing one integers (one per line), calculate the total of all the integers and append the line " Total:" followed immediately by the integer total (no spaces in between) and ending with a newline. Assumptions: (1) file indicated by filename exists in the current directory; (2) file can be empty, and if so the sum will be 0; (3) a 3 non-empty file can contain one or more lines ending with a newline; (4) each line contains a single integer and nothing else, and (5) the function returns None. Examples: append_total(" f1.txt") corresponds to the files to the right

Explanation / Answer

code:

import os
import sys
import numpy as np

def append_total(filename):
   fr = open(filename,"r")
   li = []
   total =0
   for line in fr.readlines():
       li.append(line)
       print line
       total+=int(line.strip())
   fr.close()
   fw =open(filename,"w")
   for l in li:
       fw.write(l)
   fw.write("Total:"+str(total))  

print append_total("input.txt")

input file name is input.txt

final output in file:

100
100
3
100
9
9
Total:321