150k views
5 votes
3. Sum of Numbers Assume that a file containing a series of integers is named numbers . dat and exists on the computer's disk. Design a program that reads all of the numbers stored in the file and calculates their total.

User Rveerd
by
5.8k points

1 Answer

4 votes

Answer:

The program written in Python is as follows:

file_handler = open("numbers.dat","r")

nums = 0

for line in file_handler:

try:

nums+=int(line)

except ValueError:

continue

file_handler.close()

print("Sum: "+str(nums))

Step-by-step explanation:

The file handler is used to enable the program reads content of the file numbers.dat

file_handler = open("numbers.dat","r")

This initializes the sum of numbers to 0

nums = 0

This iterates through the line of the file

for line in file_handler:

The try exception is used to prevent program crash if data other than integer is read

try:

This adds numbers on each line

nums+=int(line)

This exception is returned for data other than integers

except ValueError:

continue

This closes the file handler

file_handler.close()

This prints the calculated sum

print("Sum: "+str(nums))

User Shortduck
by
5.7k points