SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Files And Exceptions
Exercise:
Programming Exercises
Question:5 | ISBN:9780132576376 | Edition: 2

Question

Sum of Numbers
Assume that a file containing a series of integers is named numbers.txt and exists on the computer’s disk. Write a program that reads all of the numbers stored in the file and calculates their total.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Sum of Numbers Python code:

#a file containing a series of integers
#is named numbers.txt 
inputFile = "numbers.txt"
#Reads all of the numbers stored in the file 
#and calculates their total.
try:
    with open(inputFile, 'r') as file:
        numbers = file.read().split()
        total = sum(map(int, numbers))

        print(f"The total of the numbers in '{inputFile}' is: {total}")

except FileNotFoundError:
    print(f"File '{inputFile}' not found.")
except IOError:
    print(f"An error occurred while reading the file '{inputFile}'.")
except ValueError:
    print(f"The file '{inputFile}' contains non-integer values.")

Data in "numbers.txt" file:

5 
10
20
40
5
95
20
30

Executed Output:

The total of the numbers in 'numbers.txt' is: 225

 

0 0

Discussions

Post the discussion to improve the above solution.