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

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

23.77 116 94 -12.8 0 14.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') as outp:

for line in inp:

try:

num = float(line)

total = total + num

outp.write(str(total) + ' ')

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 the only 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 do this problem under def file_sum. I don't even know how to call a .txt file as a parameter.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!