71.8k views
1 vote
"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."

User Jimmy Dee
by
5.5k points

1 Answer

4 votes

Answer:

The program to this question can be described as follows:

Program:

def sum(): #defining the method main

f = open('numbers.txt','r') #open the file in r mode

total = 0#Initialize variable total to 0

for i in f: #defining a loop to calculate total of the number

num = int(i) #holding value of file in num variable

total =total+ num # adding the value in total variable

f.close() # close the file

print('Total of the number is: ',total) #print total

sum() #calling the method

Step-by-step explanation:

In the question it is declared that a file "numbers.txt" is declared, that contain the number so, the code to calculate the total of the number can be defined above and the description of the code as follows:

  • In the code a sum method is defined, inside a method, a variable "f" is declared, which uses the open method, that opens the file by using its file name.
  • In the next step, a total variable is initialized with 0, which is used in the for loop, that calculates the total of the file number, and uses a print method to print its value.