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.
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