Menu

(Solved) : Write Function Named Filesum Takes Parameter Name Text File Contains List Numbers One Line Q44003224 . . .

Write a function named file_sum that takes as a parameter thename of a text file that contains a list of numbers, one to a line,like this:

23.7711694-12.8014.999

***PYTHON 3 ONLY***

The function should sum the values in the file and writethe sum (just that number) to a text file namesum.txt.

The file must be named: file_sum.py

This is what I have for my code so far. In the’sum.txt.’ file, the number I highlighted is the only number I wantto appear in the ‘sum.txt’ file. Instead, I get all these numbersleading up to the final sum. That is not what I want and I onlywant the number 235.969 as the number. How do I make that be theonly number to appear in ‘sum.txt’ under the file_sum function inmy file_sum.py?

def file_sum(filename): total = 0 with open(filename, r) as my_file: with open(sums.txt, W) as outfile: for line in my_

saved nums.txt 1 3.77 2 116 3 94 -12.8 14.999

saved sum.txt 1 3.77 2 139.77 3 233.77 4 220.97 5 220.97 6 235.969

def file_sum(filename): total = 0 with open(filename, ‘r’) as my_file: with open(‘sums.txt’, ‘W’) as outfile: for line in my_file: numbers = line.split(‘,’) for num in numbers: total += float(num) outfile.write(str(total)) my_file.close() return totall saved nums.txt 1 3.77 2 116 3 94 -12.8 14.999 saved sum.txt 1 3.77 2 139.77 3 233.77 4 220.97 5 220.97 6 235.969 Show transcribed image text def file_sum(filename): total = 0 with open(filename, ‘r’) as my_file: with open(‘sums.txt’, ‘W’) as outfile: for line in my_file: numbers = line.split(‘,’) for num in numbers: total += float(num) outfile.write(str(total)) my_file.close() return totall
saved nums.txt 1 3.77 2 116 3 94 -12.8 14.999
saved sum.txt 1 3.77 2 139.77 3 233.77 4 220.97 5 220.97 6 235.969

Expert Answer


 

***You should have writtenoutfile.write outside the for loop. i have corrected your code:-

def file_sum(filename):
total = 0
with open(filename,’r’) as my_file:
for line in my_file:
numbers=line.split(‘,’) . . . .

OR