Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Microsoft SQL Server 2012 Unleashed

Authors: Ray Rankins, Paul Bertucci

1st Edition

0133408507, 9780133408508

More Books

Students also viewed these Databases questions

Question

1. Diagnose and solve a transfer of training problem.

Answered: 1 week ago