Menu

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

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

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

The file must be named: file_sum.py

Write in Python 3 only!

This is what I have for my code so far:

total = 0

with open(‘nums.txt’, ‘r’) as inp, open(‘sum.txt’, ‘w’) asoutp:

for line in inp:

try:

num = float(line)

total = total + num

outp.write(str(total) + ‘n’)

except FileNotFoundError:

print(‘{} is not a number!’.format(line))

print(‘Total of all numbers: {}’.format(total))

The sum should be 235.969. I do not know how to make it be theonly number to appear in my sum.txt file. What I get is this:

23.77
139.77
233.77
220.97
220.97
235.969

I only want 235.969. Also, I am completely stuck on how to dothis problem under def file_sum. I don’t even know how to call a.txt file as a parameter.

Expert Answer


Answer to Write a function named file_sum that takes as a parameter the name of a text file that contains a list of numbers, one t…

OR